4

例:

ユーザー名に「@」を追加したい場合は、handlebars.js を使用します。

@{{username}}

しかし、カスタム ヘルパーを使用して、式だけでなくテキスト ブロック全体 ("@" を含む) に適用したい場合はどうすればよいでしょうか? このようなもの...

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

{{color "@"username}}

上記のテンプレートは無効ですが、アイデアはわかります...

4

1 に答える 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>さらに良いでしょう。

于 2012-06-01T00:05:19.857 に答える