2012-11-02 2 views
3

Handlebars.js를 사용하고 있으며 해결할 수없는 문제에 갇혀 있습니다.Handlebars.js - 각각 및 getter

템플릿 내의 배열을 반복하고 싶지만, 문제는 반복자에 사용하는 표현식이 getter가 아니라 배열이라는 것입니다.

문제를 예시 코드 부분은 다음이다 :

HTML :

<script id="template" type="text/x-handlebars"> 
    Accessing directly: {{array}} <br/> 
    Accessing by getter: {{getArray}} <br/> 

    <br/> 

    Looping directly: 
    <ul> 
    {{#each array}} 
     <li>{{this}}</li> 
    {{/each}} 
    </ul> 

    <br/> 

    Looping by getter: 
    <ul> 
    {{#each getArray}} 
     <li>{{this}}</li> 
    {{/each}} 
    </ul> 
</script> 

<p id="content"></p> 

JS :

var template = Handlebars.compile($("#template").html()); 
var element = { 
    array: [0, 1, 2], 

    getArray: function() { 
     return this.array; 
    } 
}; 

$("#content").html(template(element)); 

문제는 게터를 사용 each가 없다는 것이다 아무것도. 이 내용은 jsFiddle에서 볼 수 있습니다.

getter를 사용하여이를 수행 할 수있는 명확한 방법이 있습니까? 또는 도우미 또는 보조 기능을 작성해야합니까?

감사합니다.

답변

7

{{#each}}은 배열을 예상하며 다른 것을 이해하지 못합니다.

getArray: function() { 
    return this.array; 
} 

권리 this을 가지고 : 당신은 이것에 대한 간단한 사용자 지정 도우미를 추가 할 수 있습니다, 당신은 당신이 예상하는 경우 fn.call(this)를 사용하는 것을 기억해야 할 것이다. 이런 식으로 뭔가 아마도 트릭을 할 것입니다 :

Handlebars.registerHelper('smart_each', function(a, block) { 
    if(typeof a == 'function') 
     a = a.call(this); 
    var s = ''; 
    for(var i = 0; i < a.length; ++i) 
     s += block(a[i]); 
    return s; 
}); 

데모 : http://jsfiddle.net/ambiguous/yuPfD/

당신은 조금 그것을 단장하기 위해 핸들 소스의 {{#each}} 구현을 볼 수도 있지만이 같은 것을 떠날거야 운동.

+0

멋진 대답; 그것이 내가 필요한 옳은 일이다. 감사! –

0

proper JavaScript getters을 사용하면 기술이 작동합니다. 다음은 ES6에서 사용할 수있는 클래스 사용 예제입니다. 아래 코드의 ES5 예는 this version which uses babel.io's repl을 참조하십시오.

'use strict' 

const handlebars = require('handlebars') 
const template = "{{#each letters}} {{this}} {{/each}}" 
var context 

class Alphabet { 
    get letters() { 
    return 'abc'.split('') 
    } 
} 

context = new Alphabet() 
console.log('class instance with getter methods:') 
console.log(handlebars.compile(template)(context)) 


context = { 
    letters: 'xyz'.split('') 
} 

console.log('regular object:') 
console.log(handlebars.compile(template)(context)) 

출력 :

❯ node index.js 
class instance with getter methods: 
a b c 
regular object: 
x y z 
관련 문제