Pet*_*low 4 javascript templates mustache handlebars.js
一个例子:
使用handlebars.js,如果我想将"@"附加到用户名,我会这样做:
@{{username}}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想使用自定义助手并将其应用于整个文本块(包括"@")而不仅仅是表达式,该怎么办?像这样......
handlebars.registerHelper('color', function(text) {
return text.red;
});
{{color "@"username}}
Run Code Online (Sandbox Code Playgroud)
以上模板无效,但您明白了......
你可以这样做,例如:
<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>
Run Code Online (Sandbox Code Playgroud)
<span class="username"></span>或者<hl></hl>会更好.