2014-11-06 2 views
0

나는 다음과 같은 JSON있는 경우 :핸들 바 출력 제외와 반복의 모든 필드

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

이 것 출력 다음 : 나는 HTML로 출력에 json으로 모든 필드를 원하는

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

을 :

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

그러나 어떻게이 루프를 사용하여 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를 사용하여 어떻게 달성 할 수 있습니까?

조건이 거짓 인 경우는 true를 반환하는 사용자 지정 도우미를 설정할 수

답변

1

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>