Search code examples
ractivejs

Ractivejs: How to get to work Nested properties in view


I have 2 objects results and headers being headers generated from _.keys(result[0])

r{
  data:{
    headers:['head1','head2']
    result:[
      {head1:'content1',head2:'content2'}
      {head1:'content3',head2:'content4'}
      {head1:'content5',head2:'content6'}
    ]
}

I have to create a table dinamically so I create this:

<table class="ui celled table segment">
  <thead>
    <tr>
    {{#headers}}
    <th>{{.}}</th>
    {{/headers}}
  </tr></thead>
  <tbody>
    {{#result:i}}
    <tr>
      {{#headers:h}}
        <td>{{????}}</td> <-- Here is where I fail to know what to put into
      {{/headers}}
    </tr>
    {{/result}}
  </tbody>
</table>

Can someone help me to fill in the blanks. So I can create a table that display the contents

If I remove the {{#headers}} part and I already know the elements <td>{{.head1}}</td> work perfectly the problem is that I'am generating different objects on the fly.


Solution

  • {{#result:i}}
      <tr>
        {{#headers:h}}
          <td>{{result[i][this]}}</td> 
        {{/headers}}
      </tr>
    {{/result}}
    

    The reason this works is that the <td> is repeated for each item in the headers array, because it's inside a headers section - so far, so obvious. Because of that, we can use this to refer to the current header (head1, head2 etc). The trick is to get a reference to the current row - and because you've already created the i index reference, we can do that easily with result[i]. Hence result[i][this].

    Here's a demo fiddle: http://jsfiddle.net/rich_harris/dkQ5Z/