Only the first if is being evaluated in JSRender

82 views Asked by At

I have an object that I am rendering in JSRender. Almost everything works except for the evaluation of a nested object I have.

"traits": {
  "admin": true,
  "editor": true,
  "writer": true
}

It is part of a larger object that I am sending to the template.

I have been trying to get JSRender to display an icon next to a name based on the traits.

{{if traits.admin}}
  <div class="icon iconadmin"></div>
{{/if}}
{{if traits.editor}}
  <div class="icon iconeditor"></div>
{{/if}}
{{if traits.writer}}
  <div class='icon iconwriter'></div>
{{/if}}

I have tried using an {{if}} {{else }} structure as well as a {{for}} loop but in each case the template only renders the first icon the user has in their traits object.

If I switch the code around it will successfully display, for instance, the editor icon if I move the test for editor to be evaluated first.

Is the problem that I am using an object?

2

There are 2 answers

0
Zac On

I can get the code to work using {{props}}

{{props traits}}
 {{if prop}}
    <div class="icon icon{{>key}}"></div>
  {{/if}}
{{/props}}

At that point it will iterate over the properties in the traits key and then evaluate them.

I am going to enter this as a bug.

5
BorisMoore On

It works correctly for me:

https://jsfiddle.net/BorisMoore/4cL5a0qv/

If I set

"admin": false,
"editor":true,
"writer": true

Then this template:

{{if traits.admin}}
  <div>ADMIN</div>
{{else traits.editor}}
  <div>EDITOR</div>
{{else traits.writer}}
  <div>WRITER</div>
{{/if}}


{{if traits.admin}}
  <div>ADMIN2</div>
{{/if}}
{{if traits.editor}}
  <div>EDITOR2</div>
{{/if}}
{{if traits.writer}}
  <div>WRITER2</div>
{{/if}}

outputs:

EDITOR
EDITOR2
WRITER2

{{if}}...{{else}}... will output a block only for the first true expression.

{{if}}...{{/if}} will output each time the expression is true

If it doesn't work for you can you post a jsfiddle...? Thanks.