【问题标题】:Nested helpers in handlebars (execution order)把手中的嵌套助手(执行顺序)
【发布时间】:2013-08-15 22:18:25
【问题描述】:

我有两个注册的助手:“_i”用于翻译 ui 字符串,“pluralize”用于复数字符串。我经常让它们嵌套,就像这里:

{{#_i}}{{num_hidden}} hidden {{#pluralize}}comment,comments,{{num_hidden}}{{/pluralize}}{{/_i}}

(这将导致类似“5 个隐藏的 cmets”)。

UI 字符串翻译的工作方式是在字典中查找 _i 标记内的整个字符串,然后替换它,例如西班牙语:

{{num_hidden}} {{#pluralize}}comentario escondido,comentarios escondidos,{{num_hidden}}{{/pluralize}}

然后我会在这个字符串上运行复数助手。当我们在调用 mustache 之前动态扩展视图时,这与 mustache 配合得很好。但是,使用 Handlebars 助手时,它首先执行复数助手(最内层),然后我得到一个没有翻译的 UI 字符串。

我觉得我做错了什么。

【问题讨论】:

标签: javascript handlebars.js mustache


【解决方案1】:

您可以使用一个助手和 MessageFormat.js 库代替嵌套:https://github.com/SlexAxton/messageformat.js - 它允许以不同的语言显示“消息”,包括复数和性别规则。

这里是车把助手:

Handlebars.registerHelper('i18n', function (text) {
    var options,
        compiledText;

    options  = arguments[arguments.length - 1];

    if (compiled[locale].hasOwnProperty(text)) {
        compiledText = compiled[locale][text];
    } else {
        compiledText = mf.compile(dictionary[locale][text]);
        compiled[locale][text] = compiledText;
    }

    return compiledText(options.hash);
});

dictonary 对象是一个包含所有翻译的对象:

dictionary = {
    en: {
        "You have MESSAGES_COUNT messages": "You have {MESSAGE_COUNT, plural, one {1 message} other {# messages}}",
    },
    pl: {
        "You have MESSAGES_COUNT messages": "Masz {MESSAGE_COUNT, plural, one {1 wiadomość} other {# wiadomości}}"
    }
};

compiled 对象是一种存储“消息”的缓存版本的对象,不会在每次使用时都对其进行编译。您还可以在构建时编译“消息”。

【讨论】:

    【解决方案2】:

    我最终使用了 Hogan.js 而不是 Handlebars,因为它与 mustache 和 mustache lambda 函数具有更好的兼容性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多