把手中嵌套的辅助对象(执行顺序)

Nested helpers in handlebars (execution order)

本文关键字:对象 执行 顺序 嵌套      更新时间:2023-09-26

我有两个注册的助手:用于翻译ui字符串的"_I"和用于将字符串转换为复数的"pluralize"。我经常把它们嵌套起来,比如这里:

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

(这将导致类似"5条隐藏评论"的情况)。

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

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

然后我会在这个字符串上运行复数帮助程序。当我们在调用splash之前动态扩展视图时,这对splash效果很好。然而,使用Handlebars助手,它首先执行复数形式的助手(最内部),然后我得到一个没有翻译的UI字符串。

我想我做错了什么。

您可以使用一个helper和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}}"
    }
};

CCD_ 2对象是一个存储"消息"的缓存版本的对象,以避免每次使用时都对其进行编译。您还可以在构建时编译"消息"。

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