Skip to content

Commit

Permalink
docs: Clarify which characters can be used in ICU variables and selec…
Browse files Browse the repository at this point in the history
…t values (#967)
  • Loading branch information
amannn authored Mar 30, 2024
1 parent a92b13d commit 345ab66
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
23 changes: 23 additions & 0 deletions docs/pages/docs/usage/messages.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ Dynamic values can be inserted into messages by using curly braces:
t('message', {name: 'Jane'}); // "Hello Jane!"
```

<details>
<summary>Which characters are supported for value names?</summary>

Value names are required to be alphanumeric and can contain underscores. All other characters, including dashes, are not supported.
</details>

### Cardinal pluralization

To express the pluralization of a given number of items, the `plural` argument can be used:
Expand Down Expand Up @@ -249,6 +255,23 @@ t('message', {gender: 'female'}); // "She is online."

**Note**: The `other` case is required and will be used when none of the specific values match.

<details>
<summary>Which characters are supported for select values?</summary>

Values are required to be alphanumeric and can contain underscores. All other characters, including dashes, are not supported.

Therefore, e.g. when you're mapping a locale to a human readable string, you should map the dash to an underscore first:

```tsx filename="en.json"
"label": "{locale, select, en_BR {British English} en_US {American English} other {Unknown}"
```

```tsx
const locale = 'en-BR';
t('message', {locale: locale.replaceAll('-', '_')};
```
</details>
### Escaping
Since curly braces are used for [interpolating dynamic values](/docs/usage/messages#interpolation-of-dynamic-values), you can escape them with the `'` marker to use the actual symbol in messages:
Expand Down
24 changes: 24 additions & 0 deletions packages/use-intl/test/core/createTranslator.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ it('handles formatting errors', () => {
expect(result).toBe('price');
});

it('supports alphanumeric value names', () => {
const t = createTranslator({
locale: 'en',
messages: {label: '{val_u3}'}
});

const result = t('label', {val_u3: 'Hello'});
expect(result).toBe('Hello');
});

it('throws an error for non-alphanumeric value names', () => {
const onError = vi.fn();

const t = createTranslator({
locale: 'en',
messages: {label: '{val-u3}'},
onError
});

t('label', {'val-u3': 'Hello'});
const error: IntlError = onError.mock.calls[0][0];
expect(error.code).toBe('INVALID_MESSAGE');
});

describe('t.rich', () => {
it('can translate a message to a ReactNode', () => {
const t = createTranslator({
Expand Down

0 comments on commit 345ab66

Please sign in to comment.