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

Handlebars.js - concatenating an arbitrary string within an expression

本文关键字:连接 任意 字符串 表达式 js 车把      更新时间:2023-09-26

一个例子:

使用车把.js如果我想在用户名上附加一个"@",我会这样做:

@{{username}}

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

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

上面的模板是无效的,但你明白了...

您可以这样做,例如:

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