jqueryjsrender

Use parent object property inside helper object loop Jsrender


I am sending a object branchData in ajax response to jsrender template having branch details.

branchData: Array(2)
0: {name: "M13", displayName: "Abc", url: null}
1: {name: "M01", displayName: "Xyz", url: null}

with

var helper = {
branchHoursText: "Teléfono y Horarios"
phoneText: "Teléfono"
hoursText: "Horario"
closedText: "CERRADA"
inventory: {M01: "0", M13: "1", M11: "0", M10: "0", M21: "0"} 
}

$(".branchInfo").html(branchTemplate.render(response, helpers));

I am using following code in template.

{{for branchData}}
     {{:displayName}}

    {{props ~inventory}}

    {{/props}}
{{/for}}

I want to display inventory of that branch if branchData.name == inventory.key. Something like

{{props ~inventory}}
        {{if key === name}}
            {{>prop}}
        {{/if}}}
{{/props}} 

please help !!


Solution

  • You need to access parent data (name) from inside the {{props}} tag. There are a few alternative approaches you can use. See Accessing parent data.

    For example:

    {{for branchData}}
        {{:displayName}}
    
        {{props ~inventory ~itemName=name}}
            {{if key === ~itemName}}
                {{>prop}}
            {{/if}}
        {{/props}}
    {{/for}}
    

    or

    {{for branchData itemVar="~branchItem"}}
        {{:displayName}}:
    
        {{props ~inventory}}
            {{if key === ~branchItem.name}}
                {{>prop}}
            {{/if}}
        {{/props}}
    {{/for}}
    

    See also this stackoverflow question