1

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.

Oskar Smith
  • 999
  • 2
  • 8
  • 9

1 Answers1

3

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);
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • Ah brilliant thanks - it was the 2nd argument raw flag that I was missing; it now works fine. And re. the raw JSON, I'm actually fetching it from a web service, so above example is just an simplified extraction for the OP. Thanks again. – Oskar Smith Mar 06 '12 at 14:16