Handlebars.js - concatenating an arbitrary string within an expression
handlebars.js, javascript, mustache, templates
Solution
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.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>` or `<hl></hl>` would be even better.
Problem
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...