Stacie T.
Stacie T.

Reputation: 420

Handlebars - Passing data with each

I am trying to center one of the td in table while each helper. Is it possible to do so?

Below is my code:

<table>
  <thead>
    <tr>
    {{#each item.[0]}}
        <th>{{@key}}</th>
    {{/each}}
    </tr>
  </thead>
  <tbody>
    {{#each item}}
    <tr>
        <td>{{Name}}</td>
        <td>{{Age}}</td>
    </tr>
    {{/each}}
  </tbody>
</table> 

I want it to be like this:

<thead>
    <tr>
        <th>Name</th>
        <th style="text-align:center">Age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>User 1</td>
        <td style="text-align:center">12</td>
    </tr>
</tbody>

Upvotes: 0

Views: 258

Answers (1)

Ayyub Kolsawala
Ayyub Kolsawala

Reputation: 849

var theTemplateScript = $("#entry-template").html();

var theTemplate = Handlebars.compile(theTemplateScript);


var context = {
  title: "My New Post",
  body: "This is my first post!",
  item: [{
    "Name": "Ayyub",
    "Age": 23
  }]
};


console.log("context ", context)

var theCompiledHtml = theTemplate(context);

console.log("theCompiledHtml ", theCompiledHtml);

$('.content-placeholder').html(theCompiledHtml);
var html = theTemplate(context);
.Age {
  text-align: center;
  color: red;
}
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>

<body>

  <script id="entry-template" type="text/x-handlebars-template">
    <table>
      <thead>
        <tr>
          {{#each item.[0]}}
          <th class="{{@key}}">{{@key}}</th>
          {{/each}}
        </tr>
      </thead>
      <tbody>
        {{#each item}}
        <tr>
          <td>{{Name}}</td>
          <td class="Age">{{Age}}</td>
        </tr>
        {{/each}}
      </tbody>
    </table>
  </script>
  <div class="content-placeholder">
    <table>
      <thead>
        <tr>
          {{#each item.[0]}}
          <th class="{{@key}}">{{@key}}</th>
          {{/each}}
        </tr>
      </thead>
      <tbody>
        {{#each item}}
        <tr>
          <td>{{Name}}</td>
          <td class="Age">{{Age}}</td>
        </tr>
        {{/each}}
      </tbody>
    </table>
  </div>
</body>

You can use this snippet, for reference I have added red color for font which you can remove later from the CSS file. Hope this helps :)

Upvotes: 1

Related Questions