Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery templates - nested JSON (unique key-names)

Glance this JSON for a sec. Yes, it's nested like hell. And I need it to be nested to keep the data-hierarchy.

JSON from firebug console

My problem is that the keys are not generic (due to C# Dictionary keys can't be the same). They vary depending on the data. My template looks like this so far:

<script id="customerTemplate" type="text/x-jQuery-tmpl">
        {{each $data}}
            <div class="Customer">
                <input class="CustomerId" type="hidden" value="${ $index }" />
                <div class="CustomerHeader">
                    <div class="NameAndCheckbox">
                        <input type="checkbox" checked="checked" class="CustomerCheckbox" />
                        <span class="HeadlineText">${ $index }</span>
                    </div>
                </div>
                <div class="CustomerProjectWrapper">

                    /* HOW TO ACCESS DATA WITHIN $data */
                </div>
            </div>
        {{/each}}
    </script>

As you see, I want to access the json within $data. $data's value contains JSON, but I don't know the syntax to access that.. and inside each $data's value there's also JSON.

How can I do this?

Note:

This is my jQuery code:

$.template("ctmpl", $("#customerTemplate"));

$.tmpl("ctmpl", jsonobject).appendTo("#CustomerContainer");

like image 338
KristianB Avatar asked Sep 12 '11 11:09

KristianB


1 Answers

You can use a syntax like this: {{each(index, value) array}} to have a clear idea of the index/value of what you are looping on. {{each}} can iterate through properties on an object as well.

So, if you had data like this:

var data = {
    testA: {
        testA1: {
            testA1A: "blahA1A",
            testA1B: "blahA1B" 
        },
        testA2: {
            testA2A: "blahA2A",
            testA2B: "blahA2B"  
        }
    },
    testB: {
        testB1: {
            testB1A: "blahB1A",
            testB1B: "blahB1B" 
        },
        testB2: {
            testB2A: "blahB2A",
            testB2B: "blahB2B" 
        },
    }
};

You could write a template like this:

<script id="contentTmpl" type="text/html">
    <ul>
    {{each(i, item) $data}}
        <li>${i}</li>
        <ul>
        {{each(j, subItem) item}}
            <li>${j}</li>    
            <ul>
            {{each(k, subSubItem) subItem}}
                <li>${k} = ${subSubItem}</li>
            {{/each}}
            </ul>
        {{/each}}
        </ul>
    {{/each}}
    </ul>
</script>

Sample here: http://jsfiddle.net/rniemeyer/8PLGP/

like image 145
RP Niemeyer Avatar answered Nov 07 '22 00:11

RP Niemeyer