3

I've been using icanhaz.js for some JS template rendering and it's great! However, I can't seem to grasp the idea behind rendering some complex objects, and then iterating over them.

Basically, in the header of a template I want to render a few basic strings, and then an iteration of an object, but I need to pre-process that object in another template first, as it has some additional variables.

So, it looks like this:

 <script id="tmpl_map" type="text/html">
     <h4>{{ equipment }}
     <h3>{{ number }}</h4>

     {{#rows}}
        {{.}}
     {{/rows}}
 </script>

My Javascript code is fairly simple for this:

view = {
    equipment: data.active.equipment,
    number: data.active.number,
    rows: function() {
        // This is where it all falls apart, I don't *get* this
        return function(text, render) {
           var rows = [];
           _.each(data.map.rows, function(el, index) {
               view = { row: el[0], has_split_next: el[1] };
               rows.push(ich.map_header(view));
           });

           return render(rows);
        }
    }
}

Basically, the rows have their own template because it each row has to check if has_split_next and potentially output additional HTML. From my understanding, I can't simply use the dot notation in an iteration, so I need to do this extra processing

However, all I get output is a bunch of [object Object] instance.

Bartek
  • 15,269
  • 2
  • 58
  • 65

2 Answers2

3

I figured it out, and I was totally over-complicating it. The initial issue was that my list wasn't processed as expected, what it should look like is:

rows = [{row: 'A', has_split_next: true}, {row: 'B', has_split_next: false}]

When mustache.js receives an array like this, the code is terrifically simple:

 view = { 
      equipment: data.active.equipment,
      number: data.active.number,
      rows: rows,
 }   

And the template is very simple:

{{#rows}}
        <li class='item'>{{ row }}</li>
        {{#has_split_next}}
            <li class='split'></li>
        {{/has_split_next}}
{{/rows}}

Hopefully this helps any one with confusion as to this, not sure why I was over-thinking it :-)

Bartek
  • 15,269
  • 2
  • 58
  • 65
1

You should pre process your rows array so that it's already in array format. Mustache expects an iterable object or array when you're using {#}, not a function. It's possible that the partial you're trying to use may work but I'm not sure how.

sciritai
  • 3,688
  • 1
  • 17
  • 22
  • Thanks, this helped me figured it out eventually. I was just over-complicating things. Cheers! – Bartek May 26 '11 at 15:17
  • No problem. Started using Mustache in work about 5 months ago and was trying to do some complicated stuff like that too. It's better to refactor all the data into the format you need. I find doing the template first helps to write the refactoring code as you know exactly how it should look. – sciritai May 26 '11 at 19:33