user7066345
user7066345

Reputation: 437

how would I achieve this in mustache.js?

I have the following js object:

var user = 
{
   FirstName:'John',
   MiddleName:'Jacob',
   LastName:'Smith',
}

I want to use mustache.js to display this info in an html table:

<table>
  <tr>
    <td>{{FirstName}}</td>
  </tr>
  <tr>
    <td>{{MiddleName}}</td>
  </tr>
  <tr>
    <td>{{LastName}}</td>
  </tr>
</table>

However, if the js object doesn't have a MiddleName value then the MiddleName row of the template shouldn't display because there is no MiddleName value to display. How would you structure your mustache template to accommodate this scenario?

Upvotes: 0

Views: 82

Answers (1)

MohamedSanaulla
MohamedSanaulla

Reputation: 6242

So you would do it this way:

{{#.}}
<table>
  <tr>
    <td>{{FirstName}}</td>
  </tr>
  {{#MiddleName}}
  <tr>
    <td>{{MiddleName}}</td>
  </tr>
  {{/MiddleName}}
  <tr>
    <td>{{LastName}}</td>
  </tr>
</table>
{{/.}}

Where {{#somekey}}{{/somekey}} is executed only if that somekey is present

Upvotes: 1

Related Questions