Fallback language options is missing
volkitom opened this issue · 1 comments
volkitom commented
When translation value is missing from an additional language, key is returned by the useTranslation hook. It's better to add an additional check for a fallback language and let the useTranslation return fallback value instead.
This can be done with the following modification:
const useTranslation = () => {
console.log('using translation')
router.useRouter();
let i18nObj;
i18nObj = i18n();
const translations = i18nObj.translations;
**// Add the following constant (gets value from i18nObj)**
const fallbackLng = i18nObj.fallbackLng;
i18nObj.defaultLang;
const { lang } = useSelectedLanguage();
// const [lang] = useSelectedLanguage();
**// Add the following helper function to reuse the functionality
/**
* Helper function to return stored values from translation file
*/
const getLanguageValue = (key, lang) => {
return key.split('.').reduce((previous, current) => (previous && previous[current]) || null, translations[lang]);
}**
return {
/**
* Returns the value stored for this given key (e.g. "i18n.ui.headline") in the translation file.
* The return value can be a string, a number, an array or an object.
* In case there is no entry for this key, it returns the key.
* @param key the key for looking up the translation
* @param view the mustache view for interpolating the template string
* @returns the value stored for this key, could be a string, a number, an array or an object
*/
t: (key, view) => {
**// Conditionally assign value to translation variable
let translation = getLanguageValue(key, lang) || getLanguageValue(key, fallbackLng) || key;**
try {
return Mustache__default["default"].render(translation, view);
}
catch (e) {
return translation;
}
},
};
};
martinkr commented
Hi @volkitom,
Thank you for your input. I return the key instead of a default language by default. It clearly shows the missing translation. Whereas falling back to a default language for this specific key would result in a mixture of languages.
Hope you understand the point where I am coming from.
Cheers,
Martin