Accessing outer array values from inner array in Mustache.js / ICanHaz

596 Views Asked by At

I have the following JSON, essentially an outer array of objects (Outer), each of which may contain an inner array of objects (Inner):

{ "Outer": [{"OuterName": "OuterName1",
             "Inner": [{"InnerName": "InnerName1"}, 
                       {"InnerName": "InnerName2"}]
            },
            {"OuterName": "OuterName2",
             "Inner": [{"InnerName": "InnerName3"}, 
                       {"InnerName": "InnerName4"}]
            }]
}

I have an ICanHaz template that builds an unordered list. There must be a list item for each object in each Inner array.

<script type="text/html" id="tmp">
    <ul>
        {{#Outer}}
        {{#Inner}}
        <li>
            {{OuterName}} - {{InnerName}} 
        </li>
        {{/Inner}}
        {{/Outer}}
    </ul>
</script>

The problem is, it doesn't seem to be possible to reference OuterName from within the #Inner condition. Therefore the output looks like this:

 - InnerName1
 - InnerName2
 - InnerName3
 - InnerName4

When I'm expecting :

OuterName1 - InnerName1
OuterName1 - InnerName2
OuterName2 - InnerName3
OuterName2 - InnerName4

Does anyone know how I can resolve this? Or will I just have to restructure my JSON so that the Inner array also contains the OuterName?

2

There are 2 best solutions below

1
bobthecow On BEST ANSWER

That's valid Mustache. The problem is most likely in your version of the library.

ICanHaz ships with Mustache.js v0.4.0. The current version — eight releases and sixteen months later — is 0.7.2. Switch to ICanHaz-no-mustache.js, and bring your own Mustache. That should fix it.

Here's a fiddle of your template working with the latest version of Mustache.js:

var tpl  = $('#tpl').html();

var data = { "Outer": [{"OuterName": "OuterName1",
             "Inner": [{"InnerName": "InnerName1"}, 
                       {"InnerName": "InnerName2"}]
            },
            {"OuterName": "OuterName2",
             "Inner": [{"InnerName": "InnerName3"}, 
                       {"InnerName": "InnerName4"}]
            }]
};

$('#output').html(Mustache.to_html(tpl, data));
1
maaachine On

I am not familiar with your template, but what about something like:

<script type="text/html" id="tmp">
    <ul>
        {{#Outer}}
        <li>
            {{OuterName}} - {{#Inner}}{{InnerName}}{{/Inner}}
        </li>
        {{/Outer}}
    </ul>
</script>

I apologize if this doesn't work, it seems like there's a good chance I'm just butchering the syntax. :)