Marcos Placona
Marcos Placona

Reputation: 21720

Conditional templates

I'm trying to add some logic to a dustjs template, but am struggling to put it all together.

I have Json code that looks like the following:

{
    "names": [{
        "name": "User 1",
        "isSir": true
    }, {
        "name": "User 2",
        "isSir": true
    }, {
        "name": "User 3",
        "isSir": true
    }, {
        "name": "User 4",
        "isSir": false
    }, {
        "name": "User 5",
        "isSir": false
    }, {
        "name": "User 6",
        "isSir": false
    }]
}

I then want to loop through this, and display only the first item for each variation of "isSir". The remainder items will be hidden with CSS, so I should end up with something that looks like:

I have tried using variations of {@if cond to grab only the ones who are "Sir" first, and then the others, but because I also need to keep count, so I know where I am on the loop, I then quickly moved to trying to use {@select key=.

I'm pretty new to Dust, so I'm sure I'm missing something.

Could anyone give me a hand on this?

Upvotes: 1

Views: 230

Answers (1)

smfoote
smfoote

Reputation: 5609

Dust is meant to be a logicless templating language, or at the very least, a less-logic templating language. That doesn't mean your app can't have logic, but only that the display logic should be supplied in your JSON.

The solution to your problem isn't possible in Dust with your current JSON, but if you change you JSON to:

{
    "names": [{
        "name": "User 1",
        "isSir": true,
        "isHidden": false
    }, {
        "name": "User 2",
        "isSir": true,
        "isHidden": true
    }, {
        "name": "User 3",
        "isSir": true,
        "isHidden": true
    }, {
        "name": "User 4",
        "isSir": false,
        "isHidden": false
    }, {
        "name": "User 5",
        "isSir": false,
        "isHidden": true
    }, {
        "name": "User 6",
        "isSir": false,
        "isHidden": true
    }]
}

Then you can use a template like this:

<ul>
{#names}
  <li{?isHidden} class="hidden"{/isHidden}>
    {?isSir}Sir {/isSir}{name}
  </li>
{/names}
</ul>

Upvotes: 2

Related Questions