最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handlebars.js - concatenating an arbitrary string within an expression - Stack Overflow

programmeradmin4浏览0评论

An example:

Using handlebars.js if I wanted to do append an "@" to a username I would do this:

@{{username}}

However, what if I want to use a custom helper and have it applied to the entire block of text (including the "@") and not just the expression? Something like this...

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

{{color "@"username}}

The above template is invalid, but you get the idea...

An example:

Using handlebars.js if I wanted to do append an "@" to a username I would do this:

@{{username}}

However, what if I want to use a custom helper and have it applied to the entire block of text (including the "@") and not just the expression? Something like this...

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

{{color "@"username}}

The above template is invalid, but you get the idea...

Share Improve this question edited Sep 13, 2012 at 19:32 Peter Ludlow asked May 31, 2012 at 14:32 Peter LudlowPeter Ludlow 862 silver badges5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can do this, for example:

<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.pile(source);
document.write(template({
    links: [
        {title: "prologin", prefix: "#", link: "http://prologin"},
        {title: "1.2.1", prefix: "§", link: "#paragraph-121"},
        {title: "jjvie", link: "http://twitter./jjvie"},
    ]
}));
</script>

<span class="username"></span> or <hl></hl> would be even better.

发布评论

评论列表(0)

  1. 暂无评论