Skip to content

fix: clearer explanation of string templates #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions topics/compose/compose-multiplatform-resources-usage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[//]: # (title: Using multiplatform resources in your app)

<toc-settings structure-elements="chapter" depth="3"/>
<show-structure depth="2"/>

When you've [set up the resources for your project](compose-multiplatform-resources-setup.md),
build the project to generate the special `Res` class which provides access to resources.
Expand Down Expand Up @@ -154,21 +154,34 @@ You can use special symbols in string resources:
* `\t` — for a tab symbol
* `\uXXXX` — for a specific Unicode character

You don't need to escape special XML characters like "@" or "?"
as you do [for Android strings](https://developer.android.com/guide/topics/resources/string-resource#escaping_quotes).

#### String templates

Currently, arguments have basic support in string resources:
Currently, arguments have basic support for string resources.
When creating a template, use the `%<number>` format to place arguments within the string and include a `$d` or `$s` suffix
to indicate that it is a variable placeholder and not simple text.
For example:

```XML
<resources>
<string name="str_template">Hello, %1$s! You have %2$d new messages.</string>
<string name="str_template">Hello, %2$s! You have %1$d new messages.</string>
</resources>
```

There is no difference between `%...s` and `%...d ` when using string templates with arguments from composable code,
for example:
After creating and importing the string template resource, you can refer to it while
passing the arguments for placeholders in the correct order:

```kotlin
Text(stringResource(Res.string.str_template, 100, "User_name"))
```

There is no difference between the `$s` and `$d` suffixes, and no others are supported.
You can put the `%1$s` placeholder in the resource string and use it to display a fractional number, for example:

```kotlin
Text(stringResource(Res.string.str_template, "User_name", 100))
Text(stringResource(Res.string.str_template, "User_name", 100.1f))
```

#### String arrays
Expand Down