Reputation: 607
In my app I can localize most of strings via tags, as it is described in l20n.js docs. But sometimes I have to localize dynamycally created strings. Like: document.getElementById(id).innerHTML = "some text";
I use Polymer and custom web components, so the main goal is to create one function for any localization case.
If i try document.l10n.get(string);
, I get TypeError: document.l10n.get is not a function
.
What is the best way to do it? Could not find the solution in official docs.
Upvotes: 2
Views: 396
Reputation: 766
Since document.l10n
is an instance of the L20n's View
class, you can use the formatValue
and formatValues
methods for your use-case. Please see the documentation for details.
Both methods return promises so you'll need to do something like the following:
document.l10n.formatValue('hello', { who: 'world' }).then(
hello => document.getElementById(id).textContent = hello
);
You can assign to textContent
or innerHTML
. Keep in mind that L20n allows for HTML in translations and it only sanitizes them when using the declarative data-l10n-id
approach. So if you want to manually assign to innerHTML
you might want to make sure you trust the content of the translations. In the future I'd like to add a special API to apply translations to DOM elements using the same sanitization as the declarative method (bug 1228021).
Upvotes: 1