Search code examples
templatesscopedust.js

Dust.js context issue?


I have the following partial:

<ul class="navbar">
    {#nav_links}
    <li class="navbar__link {?sub_menu}more{/sub_menu}">
        <a href="/{link}">{label}</a>
        {?sub_menu}
        <ul class="navbar__link--sub">
            {#sub_menu}
            <li class="navbar__link--sub {?sub_menu}more{/sub_menu}">
                <a href="/{link}">{label}</a>
            </li>
            {/sub_menu}
        </ul>
        {/sub_menu}
    </li>
    {/nav_links}
</ul>

With JSON:

{
    title: "page title",
    nav_links: [
        {
            link: "home",
            label:"Home"
        },
        {
            link: "products",
            label:"Products",
            sub_menu: [
                {link: "link1", label: "Product A"},
                {link: "link2", label: "Product B"},
                {link: "link3", label: "Products C", sub_menu: [
                    {link: "link3-1", label: "Sub Product A"},
                    {link: "link3-2", label: "Sub Product B"}
                ]},
            ]
        }
    ]
}

The issue I've run into is the nested sub_menu property, all sub menu items add the more class regardless if they have a nested sub_menu or not. I thought the context would have shifted like it does with link and label, however it seems to still refer to the initial sub_menu like the first conditional and section tags do. I've renamed the nested sub_menu property in the JSON and partial tag, context works correctly then. Is there a way to still use the sub_menu property name? Or reference the child property such as sub_menu.sub_menu?


Solution

  • By default, Dust will walk up the context if it doesn't find a key at a certain level. However, you're wanting to explicitly check only the current level of the context. To do this in Dust, prefix the key with a dot:

    <li class="navbar__link--sub {?.sub_menu}more{/sub_menu}">