如何为Hogan.js配置国际化

How is internationalization configured for Hogan.js?

本文关键字:配置 国际化 js Hogan      更新时间:2023-09-26

我希望使用hogan.js在浏览器中创建html表单模板。我读到hogan支持i18n,但我找不到一个例子来说明它是如何工作的。你是如何将翻译后的文本传递给hogan的,你在模板中放了什么标签,我已经看到了{{_I}}和{i18n}}?

我似乎混淆了来自Twitter的Mustache.js的旧版本,而Hogan是来自Twitter的一个独立的胡子编译器。fork确实支持用于国际化的{{_i}}标记。然后,它将调用一个名为_的全局函数,在该函数中,您可以提供自己的方法来查找转换后的值。例如

translatedStrings = {
   name: "Nom";
}
function _(i18nKey) {
   return translatedStrings[i18nKey];
}
var template = "{{_i}}Name{{/i}}: {{username}}",
    context = {username: "Jean Luc"};
Mustache.to_html(template, context);

将返回"Nom:Jean-Luc"。而霍根的国际化是通过普通的胡子lambdas实现的,例如:

translatedStrings = {
   name: "Nom";
}
var template = "{{#i18n}}Name{{/i18n}}: {{username}}",
    context = {
       username: "Jean Luc",
       i18n: function (i18nKey) {return translatedStrings[i18nKey];}
    };
Hogan.compile(template).render(context);

请参阅http://mustache.github.com/mustache.5.html了解更多关于提供lambdas的信息。因此,主要的区别在于,当使用Hogan进行渲染时,必须始终在上下文中提供查找翻译的功能,而八字胡叉将查找全局方法。

实际上,将其与其他国际化方法结合起来很容易。我们使用的是jquery-i18n-properties,这是一个支持使用.properties文件的jquery插件,其与Java兼容。

该框架尝试下载一个名为Messages.properties的文件,并根据浏览器的语言进行示例Messages_en.properties和Messages_en_US.properties。这允许快速构建翻译的层次结构。

因此,稍微改变一下slashnick的例子,并使用hogan/胡子,我写道:

var template = "{{#i18n}}Name{{/i18n}}: {{username}}",
    context = {
       username: "Jean Luc",
       i18n: function (i18nKey) {return jQuery.i18n.prop(key);}
    };
 // Init i18n
jQuery.i18n.properties(
{
name:'Messages', 
path:'some/path',
mode : 'map'
});
Hogan.compile(template).render(context);

Messages.properties文件:

Name = Name

Messages_fr.properties文件:

Name = nom

我真的看不出使用带有查找全局函数的特殊胡子版本的优势(可能是性能?)。