Using str() to localize expressions #2270
-
Hello, I'm trying to localize a property, using the str() function as specified in the doc:
The label property can take many values, but I want to localize the default one ("Default label"). This default label string is made localizable:
So extracting and building the localization files, I get the the following 'fr.ts' (for the french translation):
I would expect that my html label is translated when the lang is changed, but it does not work. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The Valid: msg('Hello world');
msg(str`Hello ${name}`)
msg(html`Hello <b>world</b>`);
msg(html`Hello <b>${name}</b>`); Invalid: msg(`Hello ${name}`) (The
This is because One quick fix would be to move the default value directly into the @property({ reflect: true })
label?: string;
render() {
return html`<label>${this.label ?? msg('Default label')}</label>`
} Or if you prefer the property to handle the default in a more natural way, you can define your own getter/setter. This way, instead of the default being set once when the element is constructed, it is dynamic based on the current locale: private _label?: string;
@property({ reflect: true })
get label() {
return this._label ?? msg('Default label');
}
set label(name: string) {
this._label = name;
}
render() {
return html`<label>${this.label}</label>`;
}
We're currently working on new localize docs on lit.dev -- I'll make sure to clarify when to use Hope that helps! |
Beta Was this translation helpful? Give feedback.
The
str
tag is only needed if you need to put expressions inside a plain string. Otherwise you can directly pass a string tomsg
.Valid:
Invalid:
(The
str
tag is needed when there are expressions because otherwise we receive a string where expressions are already interpolated into a plain string, so it wouldn't be possible to update the template with a translation and substitute a new expression into the placeholder).