使用i18next进行动态翻译/带变量翻译 [英] dynamic translation/translation with variable with i18next

查看:595
本文介绍了使用i18next进行动态翻译/带变量翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能动态翻译.在i18next中使用变量?

How come I can't translate dynamically resp. using a variable with i18next?

例如,在我的JS文件中,我得到了以下内容:
在这里,我使用一个变量并将其分配给i18n函数,但它不起作用:

For example in my JS-file I got this:
Here I use a variable and assign it to the i18n function and it doesn't work:

//this does not work:
var dynamicTranslation = "myText.toBetranslated";
console.log("translation dynamic ", !{JSON.stringify(t(dynamicTranslation))});    

在这里,我将字符串从上面直接硬编码到i18n函数中,并且确实可以工作:

Here I hardcoded the string from above directly into the i18n function and it does work:

//inserted string is the same string as in dynamic translation but this does work:           
console.log("translation static ", !{JSON.stringify(t("myText.toBetranslated"))});

结果是:

动态翻译
翻译静态正确翻译

translation dynamic
translation static correct Translation

为了解决它,我尝试通过使用setTimeout来解决它:

In order to solve it, I tried to solve it by playing around with setTimeout:

setTimeout(function() {console.log("time out translation: " + !{JSON.stringify(t(dynamicTranslation))})}, 2000);

但是它仍然会显示一个空结果:

But it would still show an empty result:

超时翻译:

time out translation:

推荐答案

这是玉的语法.第一个代码不起作用,因为它是在后端站点用玉渲染的.在这一点上,jade并没有考虑JS部分,而只是将其渲染,并将结果(连同未修改的JS代码一起)推到了前端.因此,t()函数内部具有变量的部分不会被翻译,因为它没有考虑JS代码.

It's jade syntax. The first code didn't work because it is rendered with jade at the back end site. At that point jade doesn't take the JS part into consideration but only renders it and pushes the result (along with the untouched JS code) to the front end. Therefore the part with the variable inside the t()-function is not translated, because it doesn't take the JS code into consideration.

这篇关于使用i18next进行动态翻译/带变量翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆