Dan Bunea
Dan Bunea

Reputation: 187

jsRender for in for, but for 2 different structures

Hi I have these 2 different things:

columns = {
 name:"Name",
 ref:"Reference"
}

items:[
{ id:1, name:"Dan", ref:"01" },
{ id:2, name:"Dan2", ref:"02" }]

And I need to put them in a table like:

| Name | Reference |
| Dan  | 01        |
| Dan2 | 02        |

normally this would be:

{{for columns}}
  {{:name}} {{:ref}}<br>
{{/for}}
{{for items}}
  {{:name}} {{:ref}}<br>
{{/for}}

However, my keys in the 2 objects are dynamic, so I want to so something that in javascript would be:

var header = "";
for(key in Object.keys(columns){
   header+=" "+columns[key));
}
console.log(header);
for(var i=0;i<items.length;i++){ 
  var item = items[i]; 
  var line ="";  
  for(key in Object.keys(columns){
     line+=" "+items[key);
  }
  console.log(line);
}     

Can anyone suggest anything?

Upvotes: 0

Views: 493

Answers (1)

BorisMoore
BorisMoore

Reputation: 8524

You can do it like this:

<script id="tmpl" type="text/x-jsrender">
    <table><thead><tr>
        {{props columns}}
            <th>{{:prop}}</th>
        {{/props}}
    </tr></thead>
    <tbody>
        {{for items}}
            <tr>
                {{props ~root.columns ~item=#data}}
                    <td>{{:~item[key]}}</td>
                {{/props}}
            </tr>
        {{/for}}
    </tbody></table>    
</script>

{{props}} iterates over the properties of an object - and within the {{props}} block, key is the property (field) name and prop is the value. (See http://www.jsviews.com/#propstag).

~item=#data defines a variable (a 'helper property') you can access from within the nested blocks, to easily get to 'parent data' from there. (See http://www.jsviews.com/#samples/jsr/paths).

The above assumes using the following data:

var data = {
    columns: {
        name:"Name",
        ref:"Reference"
    },
    items:[
        { id:1, name:"Dan", ref:"01" },
        { id:2, name:"Dan2", ref:"02" }
    ]
}

$("#result").html(tmpl.render(data));

Upvotes: 1

Related Questions