1

In Mustache templating, I want to check if a particular key exists in json. How can I achieve this?

newtextJS
  • 45
  • 6

2 Answers2

0

Mustache is for logic-less templating so you can't have this kind of condition in your code.

You'll need to somehow modify the JSON, either when you create it (if you have control over it), or after you receive it. For example, you could add an "isTraining" property to that particular JSON object:

    {
        "channelId": "training",
        "maxResults": 99,
        "searchRadius": 100,
        "isTraining": true
    }

And then you can use that in the Mustache template:

{{#isTraining}}
    ...
{{/isTraining}}
laurent
  • 79,308
  • 64
  • 256
  • 389
0

Mustache is logic-less. This is the kind of logic that you can do in the controller instead.

Similiar questions:

How to handle an IF STATEMENT in a Mustache template?

Check with mustache js if parameter is a specific value

Example from Khalid Dabjans answer:

json: {
    name: "James",
    isJames: true
}

And in HTML:

{{#isJames}}
    //the name is James
{{/isJames}}

{{^isJames}}
    //the name is NOT James
{{/isJames}}
Community
  • 1
  • 1
smoksnes
  • 9,330
  • 3
  • 41
  • 57