Skip to content

Comment faire un template

Pierre Besson edited this page Jun 18, 2013 · 4 revisions

Faire un template avec le HTML à générer. Ensuite ajouter en bas dans un commentaire HandleBars un exemple d'appel au template avec des données. Par exemple:

Le code du template

<table class="table table-hover">
  <caption>{{title}}</caption>
  <thead>
    <tr>
      {{#each headers}}
        <th>{{value}}</th>
      {{/each}}
      {{! will generate something like <th>FirstName</th>
      <th>LastName</th>
      <th>Address</th>
      <th>Loyalty</th> }}
    </tr>
  </thead>
  <tbody>
    {{#each collection}}
    {{! Line content}}
        <tr id="{{lineId}}">
          <td>{{value1}}</td>
          <td>{{value2}}</td>
          <td>{{value3}}</td>
          <td>{{value4}}</td>
        </tr>
   {{/each}}
  </tbody>
</table>

Exemple d'appel

{{!
  Sample object to inject in the template
    var table =  {
      title: 'Title of the tab',
      headers:[{value: 'Column 1'},{value: 'Column 2'}, {value: 'Column 3'}, {value: 'Column 4'}],
      collection: [
        {lineId: 1, value1:'ppppp', value2:'oooooo', value3: 'ssssssss', value4: 'sjchsjchsjch'},
        {lineId: 2, value1:'ppppp3', value2:'oooooo4', value3: 'ssssssss5', value4: 'sjchsjchsjch6'}
      ]
  };
  //How to use the template and insert it in the dom.
  $('div#tableToShow').html(Handlebars.templates.table(table)); 
}}