javascriptjsonicanhaz.js

iCanHaz.js + Moustache doesn't render first row in data object


I have a JSON data object and a text/html javascript template written using the Moustache syntax. I'm using iCanHaz.js as a template parser.

My problem is that the first row in the data object doesn't get displayed.

Here is my JS code:

 var data = jQuery.parseJSON('{"data":[{"title":"Title One"}, {"title":"Title Two"}]}');
 var html = ich.data_template(data);

And my Moustache template:

<script type="text/html" id="data_template">
    {{#data}}
       {{title}}<br />
    {{/data}}   
</script>

The above code outputs this as my rendered HTML:

<br />
Title Two<br />

As you can see "Title One" from the JSON object isn't displayed.

Does anyone know why? I'm taking a guess it's something to do with my JSON object not being structured correctly (arrays/objects).

Many thanks.


Solution

  • Try setting the raw flag (2nd argument) to true.

    var data = jQuery.parseJSON('{"data":[{"title":"Title One"}, {"title":"Title Two"}]}');
    var html = ich.data_template(data, true); #Note the true.
    

    Also, why are you writing your JSON as a string and parsing it? You can do:

    var data = {"data": [{"title": "Title One"}, {"title": "Title Two"}]};
    var html = ich.data_template(data, true);
    

    Without the raw flag, it returns an array of node elements, and you will need to set a root level element for it to work.

    <script type="text/html" id="data_template">
        <div>
        {{#data}}
           {{title}}<br />
        {{/data}}   
        </div>
    </script>
    

    You can test this by running the following JavaScript in your console.

    ich.addTemplate('data_template', '{{#data}}{{title}}<br />{{/data}}');
    var data = {"data": [{"title": "Title One"}, {"title": "Title Two"}]};
    var html = ich.data_template(data, true);
    console.log(html);
    
    html = ich.data_template(data);
    
    console.log(html);
    
    ich.addTemplate('data_template_root', '<div>{{#data}}{{title}}<br />{{/data}}</div>');
    
    html = ich.data_template_root(data, true);
    console.log(html);
    
    html = ich.data_template_root(data);
    
    console.log(html);