jQuery Handlebars.js:像普通的完整模板一样使用部分模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18306382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handlebars.js: Use a partial like it was a normal, full template
提问by Jonathan Dumaine
I have a template that I want to use both as a partial, and by itself from javascript.
我有一个模板,我想将它用作部分模板,并单独使用来自 javascript 的模板。
回答by Jonathan Dumaine
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.
如果您的模板是预编译的,您可以通过访问您的部分,也可以Handlebars.partials['partial-name']()
通过{{> partial}}
帮助程序从模板中调用它们。
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('myPartial', context));
myDiv.appendChild(elementFromTemplate('a-whole-template'));
myDiv.appendChild(elementFromTemplate('a-whole-template'));
Hope this helps anyone else who wants to use Handlebars like I do.
希望这可以帮助任何想像我一样使用 Handlebars 的人。
回答by Frederik Wordenskjold
It's easier to do it the other way around - to compile all your templates as normal templates, then make them available as partials:
反过来更容易 - 将所有模板编译为普通模板,然后将它们作为部分可用:
Handlebars.partials = Handlebars.templates
This makes it possible to use your templates as usual, and as partials as well:
这使得可以像往常一样使用您的模板,也可以作为部分使用:
{{> normalTemplate}}
回答by Adil
To render a partial from javascript you can use
要从 javascript 呈现部分,您可以使用
Handlebars.partials["myPartial"]()
回答by Raoul George
To use a partial from a template, simply include {{> partialName}}
.
要使用模板中的部分,只需 include {{> partialName}}
。
<script id="base-template" type="text/x-handlebars-template">
<div>
{{> person}} <!-- This is the partial template name -->
</div>
</script>
<script id="partial-template" type="text/x-handlebars-template">
<div class="person">
<h2>{{first_name}} {{last_name}}</h2>
<div class="phone">{{phone}}</div>
</div>
</script>
<script type="text/javascript">
$(document).ready(function() {
var template = Handlebars.compile($("#base-template").html());
//Aliasing the template to "person"
Handlebars.registerPartial("person", $("#partial-template").html());
template(yourData);
}
</script>