Pregunta

How can I loop a selected group/ object list only from my json data? For instance, I just want to loop "ID2" in the example below,

json,

 { 
"ID1": {
        "items":{
            "0": "VALUE1",
            "1": "VALUE2",
            "2": "VALUE3",
            "4": "VALUE4"
        }
    },
"ID2": { 
        "items": {
            "0": "VAL2-1",
            "1": "VAL2-2",
            "2": "VAL2-3"
        }
    }
}

js,

myTmpl2 = $.templates("#myTmpl2");
    $("#result2").html(
        myTmpl2.render(data2)
    );

template,

<script id="myTmpl2" type="text/x-jsrender">
{{props #data}}
    <tr>
            <td>{{:key}}</td>

                {{for prop}}
                    {{props items}}

                     <td>{{>key}} - {{>prop}}</td>

                    {{/props}}
                {{/for}}


            </tr>
{{/props}}
</script>

result,

ID1     0 - VALUE1  1 - VALUE2  2 - VALUE3  4 - VALUE4
ID2     0 - VAL2-1  1 - VAL2-2  2 - VAL2-3

The result I am after,

result,

ID2     0 - VAL2-1  1 - VAL2-2  2 - VAL2-3

Is it possible?

and btw, what does #data mean in {{props #data}} (I am using it but don't understand it!)?

can I do this if I want to select a group only - {{props #data.ID2}}??

¿Fue útil?

Solución

#data is the current data item (or data context, if you will). See http://www.jsviews.com/#assigntag for a sample illustrating this.

In fact #data is short for #view.data and #view is the current 'view'. See this sample for example: http://www.jsviews.com/#samples/jsr/paths.

Data paths such as foo.bar start at the current data item, so #data.foo.bar and foo.bar are equivalent.

In your sample above you could go straight to the ID2 object, by writing:

<tr>
    <td>ID2</td>
    {{props ID2.items}}
        <td>{{>key}} - {{>prop}}</td>
    {{/props}}
</tr>

Other variants:

{{for ID2}}
    <tr>
        <td>ID2</td>
        {{props items}}
            <td>{{>key}} - {{>prop}}</td>
        {{/props}}
    </tr>
{{/for}}

or:

{{props #data}}
    {{if key === "ID2"}}
        <tr>
            <td>{{:key}}</td>
            {{for prop}}
                {{props items}}
                    <td>{{>key}} - {{>prop}}</td>
                {{/props}}
            {{/for}}
        </tr>
    {{/if}}
{{/props}}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top