如何使用 Mustache.js 进行高级 i18n 操作?
Twitter 似乎正在使用 fork 的 Mustache.js 为其模板提供国际化?
有人可以给出一个简短的例子来说明这是如何完成的,也许还概述了众包这些翻译所必需的语义?
当然有这个简单的例子:
var template = "{{_i}}{{name}} is using mustache.js!{{/i}}"
var view = {
name: "Matt"
};
var translationTable = {
// Welsh, according to Google Translate
"{{name}} is using mustache.js!": "Mae {{name}} yn defnyddio mustache.js!"
};
function _(text) {
return translationTable[text] || text;
}
alert(Mustache.to_html(template, view));
// alerts "Mae Matt yn defnyddio mustache.js!"
但我想对如何构造 _(text) 函数和翻译表以提供条件、单数、复数等有更多的了解。解决更高级用例的示例将不胜感激。
It seems Twitter is using a fork of Mustache.js to provide i18n to its templates?
Could someone give a brief example of how this is done and perhaps also outline what semantics is necessary to crowdsource these translations?
There is of course this simple example:
var template = "{{_i}}{{name}} is using mustache.js!{{/i}}"
var view = {
name: "Matt"
};
var translationTable = {
// Welsh, according to Google Translate
"{{name}} is using mustache.js!": "Mae {{name}} yn defnyddio mustache.js!"
};
function _(text) {
return translationTable[text] || text;
}
alert(Mustache.to_html(template, view));
// alerts "Mae Matt yn defnyddio mustache.js!"
But I'd like some more insight on how to structure the _(text) function and translationTable to provide conditionals, singular, plural etc. Examples of solving more advanced use cases would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
构建更高级的案例(包括条件、循环等)的方式与常规 Mustache 库完全相同。您可以使用新的 I18N {{_i}} 开始和 {{/i}} 结束标记来包装模板的某些部分以进行翻译。
如果您的模板是:
您可以只换行第一行
并将内部部分包含在翻译映射中。
有关完整示例,请参阅 http://jsfiddle.net/ZsqYG/2/。
Structuring the more advanced cases including conditionals, loops and so on are done in the exact same way as with the regular Mustache library. You can use the new I18N {{_i}} start and {{/i}} end tags to wrap parts of your template for translation purposes.
If you template is:
you can just wrap the first line
and include the inner part in the translation map.
See http://jsfiddle.net/ZsqYG/2/ for a complete example.
我相信您想要做的是将 i18n 功能与 Mustache 一起使用。这可以通过重载 Mustache.render 方法来实现,如下所示:
I believe what you want to do is to use i18n features with Mustache. This can be achieved by overloading the Mustache.render method as follow:
我知道我并没有真正回答你的问题,但除非你计划在这个项目上花费大量时间,否则我会认真考虑将其作为数据问题。
并且:
然后只需使模板通用:
并且:
您需要维护的只是模板和数据之间的 1:1 映射。
保持简单:)
I know i'm not answering your question really, but unless you are planning on spending a lot of time on this project I would seriously consider just leaving this as a data issue.
And:
Then just make the template generic:
And:
All you need to maintain is a 1:1 mapping between templates and data.
Keep it simple :)