Rohit Choudhary
Rohit Choudhary

Reputation: 2269

How to run or condition in Dust template

I am using "dustjs-helpers": "1.6.0", with "dustjs-linkedin": "^2.6.0" .

In my template I need to check an OR condition like

if( cherry === true || berry === true)
  path/to/template1/
else 
  path/to/template2/

How do I accomplish this with the Dust helpers?

Upvotes: 3

Views: 6114

Answers (1)

Interrobang
Interrobang

Reputation: 17434

Because you're testing two different variables, you'll need two different truth tests.

You can either put this logic into your template, or into a small helper. I'll show you both ways.

Let's assume that your context looks like this:

{
  "cherry": false,
  "berry": true
}

Template method

This method requires dustjs-helpers >= 1.6.2

You'll have to include two {@eq} checks. Because you're using such an up-to-date version of Dust, you have access to the {@any} and {@none} helpers.

{@select key=cherry}
  {@eq value="true" type="boolean"/}
  {@eq key=berry value="true" type="boolean"/}
  {@any}path/to/template1{/any}
  {@none}path/to/template2{/none}
{/select}

You have to manually override the key to berry in the second truth test.

Less-Awesome Template Method

Works with all versions of dustjs-helpers.

{@eq key=cherry value="true" type="boolean"}
  path/to/template1
  {:else}
  {@eq key=berry value="true" type="boolean"}
  path/to/template1
  {:else}
    path/to/template2
  {/eq}
{/eq}

Cons: this doesn't scale, it's ugly, it repeats data.

Helper method

Doesn't require dustjs-helpers at all.

{
  "cherry": false,
  "berry": true,
  "isFruit": function(chunk, context) {
    return context.get("cherry") || context.get("berry");
  }
}

{?isFruit}
  path/to/template1
{:else}
  path/to/template2
{/isFruit}

Pros: you can add more conditions without changing your template.

Upvotes: 7

Related Questions