I have implemented i18next, and after getting help on a couple of issues all works fine. I still have issues understanding parts of the documentation on the support site.
I'm trying to replicate this part (found here):
// given resources
{
'en-US': { translation: { key: '__myVar__ are important' } }
};
i18n.t("key", { myVar: "variables" }); // -> variables are important
On my side of things, this is the JSON file:
{
"app": {"name": "mytranslation" },
"back": "Back",
"cancel": "Cancel",
"closemenu": "Close Menu",
"closeoptions": "Close options",
"currency": "Currency symbol is __currencysymbol__",
"date": "Date",
"description": "Description"
}
And the HTML:
<body>
<div data-i18n="currency"></div>
<script src="javascript/i18next-1.7.3.min.js"></script>
<script language="javascript" type="text/javascript">
i18n.init({ preload: ['en', 'fr', 'ht', 'es', 'de', 'zh', 'vi', 'pt', 'it', 'th', 'dev'] });
i18n.init({ detectLngQS: 'lang' });
i18n.init(function(t) {
$("body").i18n();
var appName = t("app.name");
});
i18n.t("currency", { currencysymbol: "$" }); //where do I place this code???
</script>
</body>
Note: jQuery 2.1.1 and jQuery Mobile 1.4.2 are loaded in the header.
I'm sure I'm not placing the various parts where they are supposed to go, as it is not working (not inserting the variable "currencysymbol"). The rest of the code works fine, as I get all the translated text.
What I'd really like to achieve is to be able to create variables that would be called as part of the translations (currency symbol, company name, company address, etc... - for affiliates purposes), and be able to replace those values as they are repeated in the translated texts.
I would like to have those variables in one place, so they are easy to adjust, and they will not be subject to the context of language changes.
In order for i18next to interpolate variables when calling the i18n()
method against part of the DOM, you must:
useDataAttrOptions
option at init timedata-i18n-options
attribute of the targeted elementYour example HTML would become:
<body>
<div data-i18n="currency"
data-i18n-options='{"currencysymbol": "$"}'></div>
<script src="javascript/i18next-1.7.3.min.js"></script>
<script language="javascript" type="text/javascript">
i18n.init({
preload: ['en', 'fr', 'ht', 'es', 'de', 'zh', 'vi', 'pt', 'it', 'th', 'dev'],
detectLngQS: 'lang',
useDataAttrOptions: true
}, function(t) {
$("body").i18n();
var appName = t("app.name");
});
</script>
</body>
Note: The options are a JSON object, therefore proper quoting is essential. In the code above, the value of the data-i18n-options
attribute is written between simple quotes for the sake of readability. But as a matter of taste, convenience, or masochism, your may opt for either of the following, also valid HTML options:
data-i18n-options={"currencysymbol":"$"}
data-i18n-options="{"currencysymbol": "$"}"
data-i18n-options="{"currencysymbol": "$"}"