Handlebars.js:使用部分像是一个正常的,完整的模板 [英] Handlebars.js: Use a partial like it was a normal, full template
问题描述
我有一个模板,我希望将它们同时用作部分内容和JavaScript本身。如果你的模板是预编译的,你可以通过 Handlebars.partials ['partial- name']()
以及通过 {{>部分}}
助手。
这很好,因为您可以编写一个效用函数来呈现模板,无论它是完整模板还是部分模板。
ex:
function elementFromTemplate(template,context){
context = context || {};
var temp = document.createElement('div');
temp.innerHTML =模板[模板]?模板[template](context):Handlebars.partials [template](context);
return temp.firstChild;
}
myDiv.appendChild(elementFromTemplate('myPartial', );
myDiv.appendChild(elementFromTemplate('a-whole-template')); code>
希望这可以帮助其他想要像我一样使用Handlebars的人。
I have a template that I want to use both as a partial, and by itself from javascript.
If your templates are precompiled, you can access your partials via Handlebars.partials['partial-name']()
as well as call them from a template via the {{> partial}}
helper.
This is nice because you can then write a utility function for rendering a template whether it be a full blown template or partial.
ex:
function elementFromTemplate(template, context) {
context = context || {};
var temp = document.createElement('div');
temp.innerHTML = templates[template] ? templates[template](context) : Handlebars.partials[template](context);
return temp.firstChild;
}
myDiv.appendChild(elementFromTemplate('myPartial', context));
myDiv.appendChild(elementFromTemplate('a-whole-template'));
Hope this helps anyone else who wants to use Handlebars like I do.
这篇关于Handlebars.js:使用部分像是一个正常的,完整的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!