Search code examples
javascriptdust.js

If Else in Dust.js


My template is

{#results}
    {#publisher}Publisher Label {/publisher}
    {#editor}Editor Label {/editor}
    {#author}Author Label {/author}
{/results}

Data is

{
    results: {
        "publisher": "Pankaj",
        "editor": "Mike",
        "writer": "Henry"
    }
}

It outputs "Publisher Label Editor Label "

I want the output "Publisher Label Editor Label writer". The logic being since writer is undefined in template it should print the key itself. How do I implement this logic in template? basically whole data should be printed.


Solution

  • As specified, you can't solve this problem just in Dust. You have a couple options, and I will elaborate on both.

    Option 1: Change Data Format

    Dust only iterates over arrays, and iteration logic is really what you want here since you want to look at all keys, not just the ones specified in the template.

    Changing your data to look more like this:

    {
      results: [
        { role: "publisher", name: "Pankaj" },
        { role: "editor", name: "Mike" },
        { role: "writer", name: "Henry" }
      ]
    }
    

    Will allow you to write your template like this (and require dustjs-helpers):

    {#results}
      {@select key=role}
        {@eq value="publisher"}Publisher Label{/eq}
        {@eq value="editor"}Editor Label{/eq}
        {@eq value="author"}Author Label{/eq}
        {@none}{role}{/none}
      {/select}
    {/results}
    

    The special {@none} helper outputs if none of the other truth tests evaluate to true.

    Option 2: Custom Dust Helper, {@iterate}

    You can write helpers to extend Dust's templating logic. Writing a helper into your context will be an easy way to extract the data you need. In this case, there's already an {@iterate} helper that's been written for you. Use it like this, after including it and dustjs-helpers:

    {@iterate key=results}
      {@select key=$key}
        {@eq value="publisher"}Publisher Label{/eq}
        {@eq value="editor"}Editor Label{/eq}
        {@eq value="author"}Author Label{/eq}
        {@none}{$key}{/none}
      {/select}
    {/iterate}
    

    Although you have to add another helper, if you can't reformat your data this may be a better option.