您可以将新上下文传递给部分:
{{> myPartial context }}
例子:
var data = {
title: "Foo Bar",
foo: ["foo1", "foo2"],
bar: ["bar1", "bar2"],
hide: {
foo: true,
bar: false
}
};
var content = "{{title}} {{> myPartial hide }}";
var partialContent = "<div class=\"{{#if foo}}hideFoo{{/if}} {{#if bar}}hideBar{{/if}}\">Hide</div>";
var template = Handlebars.compile(content);
Handlebars.registerPartial("foo", partialContent);
template(data);
输出:
<div class="hideFoo hideBar">Hide</div>
另一种方法是传递 JSON 字符串,而不是对象,使用辅助方法:
//helper
Handlebars.registerHelper("parseJSON", function(string, options) {
return options.fn(JSON.parse(string));
});
//template
{{#parseJSON '{"foo": true,"bar": true}'}}
{{> myPartial}}
{{/parseJSON}}
演示:
//Compile main template
var template = Handlebars.compile($("#template").html());
//Register partial
Handlebars.registerPartial("myPartial", $("#myPartial").html());
//Register parseJSON helper
Handlebars.registerHelper("parseJSON", function(string, options) {
return options.fn(JSON.parse(string));
});
//Your data
var data = {
title: "Foo Bar"
};
document.body.innerHTML = template(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<!-- template.html -->
<script id="template" type="text/x-handlebars-template">
<h1>{{title}}</h1>
<h3>First Partial:</h3>
{{#parseJSON '{"foo": true,"bar": false}'}}
{{> myPartial}}
{{/parseJSON}}
<h3>Second Partial:</h3>
{{#parseJSON '{"foo": false,"bar": false}'}}
{{> myPartial}}
{{/parseJSON}}
</script>
<script id="myPartial" type="text/x-handlebars-template">
<div>hide.foo: {{foo}}</div>
<div>hide.bar: {{bar}}</div>
</script>