2014-11-06 38 views
0

如果我有以下的JSON:把手輸出迭代各領域的排除

{ 
    "a": 1, 
    "b": 2, 
    "c": 3, 
    "d": 4, 
    "e": 5, 
} 

我想輸出所有的JSON場爲HTML:

<div> 
{{#each this}} 
    <p>{{@key}} - {{this}}</p> 
{{/each}} 
</div> 

這將輸出以下:

<div> 
    <p>a - 1</p> 
    <p>b - 2</p> 
    <p>c - 3</p> 
    <p>d - 4</p> 
    <p>e - 5</p> 
</div> 

但是,我怎麼會用這個循環從ITE排除領域c定量:

<div> 
{{#each this}} 
    {{#if key does not equal 'c'}} 
     <p>{{@key}} - {{this}}</p> 
    {{#if key does not equal 'c'}} 
{{/each}} 
</div> 

使得輸出是:

<div> 
    <p>a - 1</p> 
    <p>b - 2</p> 
    <p>d - 4</p> 
    <p>e - 5</p> 
</div> 

怎麼可以這樣使用Handlebars.js能實現嗎?

回答

1

你可以建立一個自定義的助手返回true,當條件爲假

var data = { 
 
    "a": 1, 
 
    "b": 2, 
 
    "c": 3, 
 
    "d": 4, 
 
    "e": 5, 
 
}; 
 

 
var source = $("#entry-template").html(); 
 

 

 
Handlebars.registerHelper("notEqual", function(target, condition, options) { 
 

 
    if (target !== condition) { 
 
    return options.fn(this); 
 
    } else { 
 
    return options.inverse(this); 
 
    } 
 

 
}); 
 
var tempalte = Handlebars.compile(source); 
 

 
$("body").append(tempalte(data));
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script id="entry-template" type="text/x-handlebars-template"> 
 
    <div> 
 
    {{#each this}} 
 
     {{#notEqual @key 'c'}} 
 
     <p>{{@key}} - {{this}}</p> 
 
     {{/notEqual}} 
 
    {{/each}} 
 
    </div> 
 
</script>