Search code examples
keynested-loopsparentjsrender

Access parent variable from nested block in JsRender


How can I access props's key from a nested for?

{{props object.items}}
    {{:key}}
    {{for prop.other_items}}
        {{:key}} //here I want to print the key from props

I've tried:

{{:key}}
{{:#key}}
{{:#parent.key}}
{{:#parent.parent.key}}
{{:~root.key}}

Solution

  • Here are three alternative ways:

    Provide the key as a contextual template variable, so it is available in the {{for}} block:

    {{props object.items}}
        {{:key}}
        {{for prop.other_items ~outerKey=key}}
            Outer key: {{:~outerKey}}
       {{/for}}
    {{/props}}
    

    Provide the data item of the {{props}} block (the {key: ..., prop: ...} object) as a contextual template variable, so it is available in the {{for}} block:

    {{props object.items itemVar="~outerProp"}}
        {{:key}}
        {{for prop.other_items}}
            Outer key: {{:~outerProp.key}}
        {{/for}}
    {{/props}}
    

    Step up through the parent views (array view, then props item view) and get the data item (the {key: ..., prop: ...} object):

    {{props object.items}}
        {{:key}}
        {{for prop.other_items}}
            Outer key: {{:#parent.parent.data.key}}
        {{/for}}
    {{/props}}
    

    And here is a link to a related reply to a previous question from Matias: https://stackoverflow.com/a/31362057/1054484