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

4

一个例子:

使用handlebars.js,如果我想将“@”附加到用户名上,我可以这样做:

@{{username}}

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

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

{{color "@"username}}

上述模板无效,但你可以理解为...
1个回答

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> 更好。

"
"使用或者标签会更好。"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接