How to access parent data properties in JsRender nested templates

前端 未结 2 846
一生所求
一生所求 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条回答
  •  萌比男神i
    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}} 
         
  • index: {{>color}} (match)
  • {{else}}
  • index: {{>color}}
  • {{/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}}
         
  • index: {{>color}} (match)
  • {{else}}
  • index: {{>color}}
  • {{/if}} {{/for}}

    Step up through the parent view objects, and get the data view:

    {{for testData}}
       {{if #parent.parent.data.foo.color===color}}
         
  • index: {{>color}} (match)
  • {{else}}
  • index: {{>color}}
  • {{/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}}
         
  • index: {{>color}} (match)
  • {{else}}
  • index: {{>color}}
  • {{/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

提交回复
热议问题