문제

Here is a jsfiddle of the following to play with. Say I have this JSON data:

{
    "people": [
        {
            "name": "Bob",
            "eye-color": "Green"
        },
        {
            "name": "Jill",
            "eye-color": "Blue"
        },
        {
            "name": "James",
            "eye-color": "Green"
        }
    ]
}

If I wanted to output all of the peoples' names using dust.js, I would set up the template like so:

<ul>
    {#people}
    <li>{name}</li>{~n}
    {/people}
</ul>

However, what if:

1) I only wanted to output the names of people with "Green" eyes? Is there a way to do that using conditionals in dust?

2) I only wanted to output the first two names, regardless of eye color

3) I only wanted to output the second person's name, regardless of eye color

EDIT: Adding a fourth and fifth scenario:

4) I only want to display the second and third names (ie index X to index Y)

5) I only want to output the first two names of people with green eyes (say the list of people went on much longer than the 3 shown above, including more green-eyed people that won't be displayed).

And one more question:

Say my JSON has a key / value pair like the following:

{ "tags": ["tag1", "tag2", "tag3"] }

Is there a way to use {@eq} to check if it contains "tag2" for example?

도움이 되었습니까?

해결책

You can make all three work, but you will need to use Dust helpers.

1: You need the @eq helper (I'm also changing the key from eye-color to eyeColor because dashes can confuse Dust.

<ul>
    {#people}
        {@eq key=eyeColor value="Green"}
            <li>{name}</li>{~n}
        {/eq}
    {/people}
</ul>

2: You need the @lt helper, along with $idx ($idx is the index of the current item in the array, where the first item is 0).

<ul>
    {#people}
        {@lt key=$idx value=2}
            <li>{name}</li>{~n}
        {/lt}
    {/people}
</ul>

3: You need the @eq helper, along with $idx

<ul>
    {#people}
        {@eq key=$idx value=1}
            <li>{name}</li>{~n}
        {/eq}
    {/people}
</ul>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top