How to access parent data properties in JsRender nested templates

前端 未结 2 815
一生所求
一生所求 2021-01-19 04:14

http://jsfiddle.net/tQnVt/621/

This fiddle illustrates my problem.

Say I am binding a JSON onto view with the help of jsrender templates.

v         


        
相关标签:
2条回答
  • 2021-01-19 04:55

    You need to write

    {{if xxx.foo.color===color}}
    

    where xxx is the parent data - in your case the vm you passed in as root data.

    (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:

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

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

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

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

    I added all of them to your jsfiddle: http://jsfiddle.net/tQnVt/625/

    See also this related reply: https://stackoverflow.com/a/34441881/1054484

    0 讨论(0)
  • 2021-01-19 05:18

    Also, you can to use #parent. Please see link to the docs.

    0 讨论(0)
提交回复
热议问题