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

标签 javascript templates mustache handlebars.js

一个例子:

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

@{{username}}

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

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

关于javascript - Handlebars.js - 在表达式中连接任意字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10835669/

相关文章:

backbone.js - 防止 Mustache 从缓存中加载模板

javascript - ES6 Symbol 能保证 100% 唯一标识符吗?

javascript - 使用 : Need Javascript code that gets the inner width/height of screen onload into width/height style variables

具有嵌套模板的 Javascript 框架或 knockoutjs 库

c++ - Stockfish 12 源代码 : Templates replacing function parameters

json - Mustache.js 循环遍历 JSON 数据

javascript - 如何访问 setTimeout 内部产生的值?

javascript - 使用 React 单击时输入的值更新 URL

css - Bokeh 图覆盖其他内容

javascript - 如何在 JavaScript 中将 json 哈希值转换为数组哈希值?