2016-02-08 18 views
2

我想要做什麼:定義對象和它傳遞給部分

{{>myPartial foo={bar:1} }} 

我想在它傳遞給部分定義的對象。那可能嗎?


我知道這是可能通過現有的對象像

{{>myPartial foo=foo}} 

但我想我的標記內定義我的對象。

爲什麼?基本上,因爲它只是定義佈局。我想避免在後端確定佈局決策。
我的部分是表佈局,我想隱藏特定的列。但是,使用像

{{>myPartial hideFoo=true hideBar=true}} 

多個屬性,而不是

我想用一個單一的對象hide

{{>myPartial hide={foo:true,bar:true} }} 
+0

我的答案是否適合您? –

+0

如果您發佈的問題,請提供反饋,如果有人回答,所以即將到來的用戶會知道答案是否有幫助。 –

回答

1

您可以通過一個新的上下文部分:

{{> 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>