2012-05-24 33 views
4

我有一個JSON字符串:如何使用ICanHaz for mustache javascript模板引擎?

{ 
    "items": [ 
     {"name": "red" }, 
     {"name": "blue" } 
    ], 
    "test" : { 
     "items" :[ 
      { "name" : "Hello" }, 
      { "name" : "World" } 
     ] 
    } 
} 

如何打印出

<li>Hello</li> 
<li>World</li> 

我與下面的模板嘗試,但它不工作。它會打印「紅色和藍色」。我無權訪問更改JSON字符串,我只能操作模板。

{{#test}} 
    {{#items}} 
    <li>{{name}}</li> 
    {{/items}} 
{{/test}} 

回答

3

出於某種原因,下面的代碼:

<head> 
<script src="https://github.com/andyet/ICanHaz.js/raw/master/ICanHaz.js"></script> 

<script> 
function clicked() 
{ 
     ich.addTemplate("user", "{{#test}} {{#items}} <li>{{name}}</li>\n {{/items}} {{/test}}"); 
     document.getElementById("result").innerHTML = ich.user(userData); 
} 

var userData = { 
    "items": [ 
     {"name": "red" }, 
     {"name": "blue" } 
    ], 
    "test" : { 
     "items" :[ 
      { "name" : "Hello" }, 
      { "name" : "World" } 
     ] 
    } 
}; 

</script> 

</head> 
<body> 
    <button onclick="clicked()">CLICK</button> 
    <ul id="result"><li>Result</li></div> 
</body> 

給我到底:

  • 你好
  • 世界

所以,你的模板應該是正確的。