【问题标题】:Handlebars.js - concatenating an arbitrary string within an expressionHandlebars.js - 在表达式中连接任意字符串
【发布时间】:2012-05-31 14:32:21
【问题描述】:

一个例子:

如果我想在用户名上附加一个“@”,请使用 handlebars.js:

@{{username}}

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

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

{{color "@"username}}

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

【问题讨论】:

    标签: javascript templates mustache handlebars.js


    【解决方案1】:

    你可以这样做,例如:

    <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>
    

    &lt;span class="username"&gt;&lt;/span&gt;&lt;hl&gt;&lt;/hl&gt; 会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-10
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多