JsRender Access parent index in nested template

僤鯓⒐⒋嵵緔 提交于 2020-01-03 05:19:29

问题


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.


回答1:


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}}



回答2:


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'}
   ]
}];



回答3:


There is also a syntax to walk up the tree.

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



来源:https://stackoverflow.com/questions/15943139/jsrender-access-parent-index-in-nested-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!