如何在JsRender嵌套模板中访问父数据属性 [英] How to access parent data properties in JsRender nested templates
问题描述
http://jsfiddle.net/tQnVt/621/
这个小提琴说明了我的问题.
This fiddle illustrates my problem.
说我借助jsrender模板将JSON绑定到视图上.
Say I am binding a JSON onto view with the help of jsrender templates.
var vm = {
foo: {color: "red",otherObjectToMatch:"object"},
testData: [{color: "red"}, {color: "yellow"}, {color: "blue"}]
};
对象vm
具有2个属性-
1)一个普通的对象
2)对象数组.
Object vm
has 2 properties-
1) a plain object
2) array of objects.
模板-
<script id="template" type="text/x-jsrender">
<p>
{{:foo.color}}
</p>
<ul>
{{for testData}}
<li>index: {{>color}}</li>
{{/for}}
</ul>
</script>
我想通过其属性与普通对象#1
进行匹配,如果它的属性颜色与循环中的属性匹配,则将应用某些类.
I want to match from plain object #1
by its property where if its property color matches with the property in loop then will apply some class.
我尝试过
<p>
{{:foo.color}}
</p>
<ul>
{{for testData}}
{{if foo.color=={{>color}} }}
<li class='match'>index: {{>color}}</li>
{{else}}
<li>index: {{>color}}</li>
{{/if}}
{{/for}}
</ul>
这是失败的尝试.我找不到如何与jsrender中的其他对象匹配.
This is a failed try. I can't find how to match with other objects in jsrender.
推荐答案
您需要编写
{{if xxx.foo.color===color}}
其中xxx
是父数据-在您的情况下,您是作为根数据传入的vm
.
where xxx
is the parent data - in your case the vm
you passed in as root data.
(关于"视图层次结构"的全部内容-请参阅: http://www.jsviews.com/#views .另请参见特定主题访问父数据)
(It's all about the 'view hierarchy' - see: http://www.jsviews.com/#views. See also the specific topic Accessing parent data)
以下几种获取父视图数据的方法:
Here are several different ways to get to the data on the parent view:
访问~root
,这是根数据的快捷帮助器:
Access ~root
which is a shortcut helper for the root data:
{{for testData}}
{{if ~root.foo.color===color}}
<li class='match'>index: {{>color}} (match)</li>
{{else}}
<li>index: {{>color}}</li>
{{/if}}
{{/for}}
创建上下文模板参数~foo
,将foo
属性从父数据传递到嵌套模板上下文:
Create a contextual template parameter ~foo
to pass the foo
property from parent data through to the nested template contexts:
{{for testData ~foo=foo}}
{{if ~foo.color===color}}
<li class='match'>index: {{>color}} (match)</li>
{{else}}
<li>index: {{>color}}</li>
{{/if}}
{{/for}}
逐步遍历父级view
对象,并获得数据视图:
Step up through the parent view
objects, and get the data view:
{{for testData}}
{{if #parent.parent.data.foo.color===color}}
<li class='match'>index: {{>color}} (match)</li>
{{else}}
<li>index: {{>color}}</li>
{{/if}}
{{/for}}
使用view.get()
帮助器找到类型为"data"
Use the view.get()
helper to find the parent of view of type "data"
{{for testData}}
{{if #get("data").data.foo.color===color}}
<li class='match'>index: {{>color}} (match)</li>
{{else}}
<li>index: {{>color}}</li>
{{/if}}
{{/for}}
我将所有这些添加到您的jsfiddle中: http://jsfiddle.net/tQnVt/625/
I added all of them to your jsfiddle: http://jsfiddle.net/tQnVt/625/
另请参阅以下相关回复: https://stackoverflow.com/a/34441881/1054484
See also this related reply: https://stackoverflow.com/a/34441881/1054484
这篇关于如何在JsRender嵌套模板中访问父数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!