Шаблоны усов: вложенные шаблоны
Как я могу использовать вложенный шаблон внутри усов? Есть ли способ сделать то же самое?
var tmpl="{{#data}}
{{values}}
Name: {{name}}
//{{another_templ({{name.value}})}}
{{/values}}
{{/data}}"
Надеюсь, вы, ребята, задали вопрос. Я не добавил символ escape для js validity, так как код разбивается на разные строки.
Ответы
Ответ 1
Вы можете использовать лямбда для размещения шаблона:
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);
Ответ 2
Я сделал пример вложенных шаблонов в 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>
Затем 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 );
Ответ 3
Вот метод, в котором мы выполняем замену строк перед компиляцией шаблонов.
Subtemplates вызывается в шаблонах:
{{#template}} insertTheNameOfYourSubTemplateHere {{/шаблон}}
templates = {}
function compileTemplates(templateNamesArray) {
for (index in templateNamesArray) {
var templateName = templateNamesArray[index];
var baseHTML = $('#' + templateName).html();
var start = baseHTML.indexOf("{{#template}}");
while(start != -1) {
var end = baseHTML.indexOf('{{/template}}', start);
var nestedTemplateName = baseHTML.slice(start + "{{#template}}".length, end);
var nestedTemplateEl = $('#' + nestedTemplateName);
if (nestedTemplateEl.length == 0) {
throw "Could not find nested template '" + nestedTemplateName + "' for the template '" + templateName + "'";
}
baseHTML = baseHTML.slice(0, start) + nestedTemplateEl.html() + baseHTML.slice(end + '{{/template}}'.length);
start = baseHTML.indexOf("{{#template}}", start);
}
templates[templateName] = Handlebars.compile(baseHTML);
}
}
compileTemplates(["templateActiveThreadTab", "templateActiveThreadContent", "templateTodoItem"]);