Handlebars.js - 连接表达式中的任意字符串

时间:2012-05-31 14:32:22

标签: javascript templates mustache handlebars.js

一个例子:

使用handlebars.js,如果我想在用户名中添加“@”,我会这样做:

@{{username}}

但是,如果我想使用自定义助手并将其应用于整个文本块(包括“@”)而不仅仅是表达式,该怎么办?像这样......

handlebars.registerHelper('color', function(text) {
    return text.red;
});

{{color "@"username}}

上述模板无效,但您明白了......

1 个答案:

答案 0 :(得分:6)

您可以这样做,例如:

<script id="template" type="text/x-handlebars-template">
    <ul>
        {{#each links}}
        <li><a href="{{ url }}">{{{color prefix title}}}</a></li>
        {{/each}}
    </ul>
</script>
<script>
Handlebars.registerHelper("color", function(prefix, title) {
    return '<span style="color: blue">' + (prefix ? prefix : "@") + title + '</span>';
}); // "@" is the default prefix

source = document.getElementById("template").innerHTML;
template = Handlebars.compile(source);
document.write(template({
    links: [
        {title: "prologin", prefix: "#", link: "http://prologin.org"},
        {title: "1.2.1", prefix: "§", link: "#paragraph-121"},
        {title: "jjvie", link: "http://twitter.com/jjvie"},
    ]
}));
</script>

<span class="username"></span><hl></hl>会更好。