Search code examples
dust.js

Dustjs - Loop iteration as ___


In my Models, variables share identical names, like name, or slug. This causes a problem, because I loop through one, and in each iteration, I loop through the other model, but in the inner loop, when I use {slug} I cannot access the 'parent" slug.

I've solved this by creating a new scope immediately after I start a loop, and put a parameter in it to name the iteration, like so:

{#categories}{#. category=.}
    <section class="category {category.slug}">
        <h2 class="name">
            <a href="/{category.slug}">
                {category.name}
            </a>
        </h2>
        {#category.forums}{#. forum=.}
            <article class="forum {forum.slug}">
                <h3 class="name">
                    <a href="/{category.slug}/{forum.slug}">
                        {forum.name}
                    </a>
                </h3>
                <p class="description">
                    {forum.description}
                </p>
            </article>
        {/.}{/category.forums}
    </section>
{/.}{/categories}

Since this works, what my question is, is, "How can I name the iteration in the same tag that starts the loop?" {#categories category=.} does not work.

I can live with what I've got, but I'm trying to clean it up as much as possible.


Solution

  • You're on the right track. Instead of passing the current context as a parameter, pass the previous context instead.

    {#categories}
        <section class="category {slug}">
            <h2 class="name">
                <a href="/{slug}">
                    {name}
                </a>
            </h2>
            {#forums category=.}
                <article class="forum {slug}">
                    <h3 class="name">
                        <a href="/{category.slug}/{slug}">
                            {name}
                        </a>
                    </h3> 
                    <p class="description">
                        {description}
                    </p>
                </article>
            {/forums}
        </section>
    {/categories}