Search code examples
javascriptjquerymustache

Condition Based Data Rendering In Mustache.js


I have Json data like

[{"Answer":"0"},{"Answer":"1"},{"Answer":"1"},{"Answer":"0"}]

I want to display right.png if the answer is 1 else i want to display wrong.png.

How Can I check the value of "Answer" before rendering the correct Image ? I am using Mustace.js template engine for this


Solution

  • Make them true/false instead of 1/0. You can use inverted sections to test against the boolean.

    [{"Answer":false},{"Answer":true},{"Answer":true},{"Answer":false}]
    

    and in your template:

    <img src="{{#Answer}}right.png{{/Answer}}{{^Answer}}wrong.png{{/Answer}}" />
    

    From Doc

    An inverted section opens with {{^section}} instead of {{#section}}. The block of an inverted section is rendered only if the value of that section's tag is null, undefined, false, or an empty list.

    If you use handlebars.js it gives you more flexibility than this to specify if else conditions