A convenient way to translate strings in JavaScript code
See original GitHub issueSvelte-i18n formatting gives a store that reproduce a function that translate a given word, meaning: _: () => store and the store has value of a function: (message) => translation
This is fine, and on Svelte files the syntax $_(messsage)
works great, first the syntax ($_)
tells Svelte to subscribe to the store value, and the invocation with the parameter (message) gets the translated string.
However, if you can’t use the convenient syntax $_(message)
in a javascript/typescript file you use with your svelte project, since $_
isn’t defined symbol of JS.
In order to be able to use this syntax, I had to write the following utility code, which I suggest this project to adapt to make life easier for people:
import { derived } from 'svelte/store';
import { format } from 'svelte-i18n';
function $_(messsage: string) {
return derived(format, ($format) => $format(messsage));
}
This function returns (as I believe it should) a store that represents the translated value of the message.
This allow up for example to call in JavaScript/TypeScript code some custom_alert($_('important-warning-message'))
, while custom_alert
is a function takes a store for a string and display it to the user as an alert.
This alert should update the translation of the message if the locale has been changed.
Do you agree? Do you believe we should have another convention?
Issue Analytics
- State:
- Created 2 years ago
- Comments:9 (2 by maintainers)
Top GitHub Comments
This issue has been addressed here https://github.com/kaisermann/svelte-i18n/issues/124
However, I can agree that it is not the nicest thing to write. I got it working creating the following function:
Thank! Good to know. I solved it with my a store and loading the message in the component.