How to run or condition in Dust template

狂风中的少年 提交于 2019-12-04 14:03:36

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!