Har*_*rry 16 javascript template-engine mustache
如何在胡子中使用嵌套模板?有没有办法做同样的事情?
var tmpl="{{#data}}
{{values}}
Name: {{name}}
//{{another_templ({{name.value}})}}
{{/values}}
{{/data}}"
Run Code Online (Sandbox Code Playgroud)
希望你们有问题.我没有为js有效性添加转义字符,因为代码分为不同的行.
您可以使用lambda来嵌套模板:
function nested_template(template_string, translate) {
return function() {
return function(text, render) {
return Mustache.to_html(template_string, translate(render(text)));
};
};
}
var template_string =
"{{#data}}"+
"{{values}}"+
"Name: {{name}}"+
"{{#another_templ}}{{name}}{{/another_templ}}"+
"{{/values}}"+
"{{/data}}";
var another_template_string = "<b>{{name}}</b>"; // for example
var view = {
data: {
values: {
name: "Test"
}
},
another_templ: nested_template(another_template_string, function(text) {
return {name: text};
});
};
var result = Mustache.to_html(template_string, view);
Run Code Online (Sandbox Code Playgroud)
小智 8
我在jsFiddle上做了一个嵌套模板的例子.这里详细说明:
首先,设置您的HTML
<div class="main"><!-- content here --></div>
<script type="text/html" id="tpl">
{{#data}}
{{#names}}
Name: {{name}}
{{#nested}}{{name}}{{/nested}}<br>
{{/names}}
{{/data}}
</script>
<script type="text/html" id="tpl-nested">
— <b>{{name}}</b>
</script>?
Run Code Online (Sandbox Code Playgroud)
然后是javascript(使用jQuery)
function renderNested(template_string, translate) {
return function() {
return function(text, render) {
return Mustache.to_html(template_string, translate(render(text)));
};
};
}
var template = $("#tpl").html();
var nested_template = $("#tpl-nested").html();
var model = {
data: {
names: [
{ name: "Foo" },
{ name: "Bar" }
],
nested: renderNested(nested_template, function(text) {
return { name: text };
})
}
};
var result = Mustache.to_html(template, model);
$(".main").html( result );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18254 次 |
| 最近记录: |