Is there a way to get the translation from method param and force the translation in that language ?
sanjanind opened this issue · 1 comments
sanjanind commented
something like this
const useTranslation = (language?: string) => {
const router = useRouter();
let i18nObj: I18N;
i18nObj = i18n() as I18N;
const translations: Dictionary = i18nObj.translations;
const defaultLang: string = i18nObj.defaultLang;
const lang = language || useSelectedLanguage().lang || defaultLang;
The method also needs to wrapped inside a callback as it is not taking updated useSelectedLanguage.
import { useRouter } from "next/router";
import { useCallback } from "react";
import i18n from "./../index";
import { Dictionary, I18N } from "../types";
import useSelectedLanguage from "./use-selected-language";
import Mustache from "mustache";
/**
* Provides the t() function which 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.
* @returns t(key: string): any function
*/
const useTranslation = (lang?: string) => {
const router = useRouter();
let i18nObj: I18N;
i18nObj = i18n() as I18N;
const translations: Dictionary = i18nObj.translations;
const defaultLang: string = i18nObj.defaultLang;
const language = lang || useSelectedLanguage().lang || defaultLang;
/**
* 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
*/
const translation = useCallback(
(key: string, view?: object): any => {
let value: any = key
.split(".")
.reduce(
(previous: any, current: string) =>
(previous && previous[current]) || null,
translations[language]
);
let translation: any = value || key;
try {
return Mustache.render(translation, view);
} catch (e) {
return translation;
}
},
[language]
);
return {
t: translation,
};
};
export { useTranslation };
martinkr commented
Hi @sanjanind,
Thank you for reaching out. I am not 100% clear about the intention of your query.
Would you mind elaborating on your use-case and the code snippet?
Thank you in advance,
Martin