'How to obtain the language of the string returned by i18next.t?
Let's say I have two translation resources (i.e. languages). One resource contains values for all the keys used in the software. This resource (here referred to as "en") is configured as fallback. The other resource (here referred to as "cn") does not have values for all keys. Let's assume the default language is "cn".
Now we can look up a key using const translation = t("some_key")
. Edit: Thus, it could be that translation
is now taken from "cn" or "en", depending on whether it is defined in "cn".
How to determine the language of translation
; or more generally, how to have i18next look up some key and also return information about the used resource?
I'm not interested in approaches scanning all the resources for translation
, nor in heuristic approaches based on the contents of translation
.
Reason for the question: I want to apply the correct lang
attribute in the browser on a certain DOM element. The localization is run on the server-side and transmitted via JSON – so this is not about i18next-react
.
Solution 1:[1]
internally i18next has a resolve function that returns the used languageā¦
You may try to access i18next.translator.resolve(key, options) but like said this is undocumented and not an official public interface.
Edit: Since v21.7.0 there is a new option returnDetails
that can be set to true to get all relevant information.
const resolved = t('key', { returnDetails: true });
resolved.res;
resolved.usedKey;
resolved.exactUsedKey;
resolved.usedNS;
resolved.usedLng;
Solution 2:[2]
Maybe you can try to get the locale for i18n. For example, in Vue 2, you can get it with:
let lang = this.$i18n.locale //return lang set ('es', 'en', 'cn', 'fr', etc)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | David May |