how to use ICanHaz for moustache javascript template engine?

607 views Asked by At

I've a JSON string:

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

How do I print out

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

I tried with the template below but it doesn't work. It instead prints "Red and blue". I don't have access to change the JSON string, I have to manipulate the template only.

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

There are 1 answers

0
Alexander Pavlov On

For some reason, the following code:

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

gives me exactly:

  • Hello
  • World

So, your template should be correct.