svizec
svizec

Reputation: 1

JsRender Access parent index in nested template

I have a problem with accessing parent index in nested template. Trying to send #index as parameter in a template, but it doesn't work (http://jsfiddle.net/Xsrdb/).

<script id="firstTemplate" type="text/x-jsrender">
     {{for segments}}
        <b>{{:#index}}</b>
    {{/for}}
    {{for segments tmpl='#secondTemplate' ~parent_index=#index}}
        <b>{{:#index}}</b>
    {{/for}}
</script>

<script id="secondTemplate" type="text/x-jsrender">
    <div>
        {{>~parent_index/}}
        <i>{{>name/}}</i>
    </div>
</script>

Does anybody know how this can be solved?

Thanks in advance.

Upvotes: 0

Views: 3540

Answers (3)

pedz
pedz

Reputation: 2349

There is also a syntax to walk up the tree.

http://borismoore.github.io/jsrender/demos/step-by-step/11_accessing-parent-data.html

Upvotes: 0

BorisMoore
BorisMoore

Reputation: 8524

Your second template, which you can write as {{for segments tmpl='#secondTemplate' ~parent_index=#index/}} is setting ~parent_index to the #index at that point, but #index at that point is undefined, since you are not in a repeating template (i.e. an 'item' view).

If you use data such as the following the index will show up:

var data = [{
   segments: [
       {name: 'a'},
       {name: 'b'}
   ]
},{
   segments: [
       {name: 'x'},
       {name: 'y'}
   ]
}];

Upvotes: 1

dugokontov
dugokontov

Reputation: 4622

In an example you provided, you can simply use {{>#index}} in secondTemplate to get index of an element.

<script id="secondTemplate" type="text/x-jsrender">
    <div>
        <b>{{>#index}}</b>
        <i>{{>name/}}</i>
    </div>
</script>

Here is sample in jsFiddle for this: http://jsfiddle.net/Xsrdb/1/

Note that if you need index of parent node, you can use:

{{>#parent.index}}

Upvotes: 2

Related Questions