Search code examples
jqueryjquery-templates

Nested eachs in jQuery template


How can I get the parent $value on a nested {{each}}? I would prefer a "direct" solution, without having to create a 2nd template, and use it from the first one.


Solution

  • You can just do this: ${ parentItem.Name }, if the parent item was called parentItem and the desired member variable was called Name. Here is an example, based loosely on the movie example in the jQuery API docs for {{each}}:

    Template:

    <li>
        Title: ${Name}.<br />
        {{each(i, edition) Editions}}
            ${i + 1}: <em>${edition.Name}. </em><br />
            Languages: <br />
            {{each(i, language) Languages}}
                ${language} (${$data.Name}, ${edition.Name}) <br />  
            {{/each}}
            <br />
        {{/each}}
    </li>
    

    Data (only one item for this example):

    var movies = [
        {
            Name: "City Hunter",
            Editions: [
                {
                    Name: "Original", 
                    Languages: ["Mandarin", "Cantonese"]
                },
                {
                    Name: "DVD",
                    Languages: ["French", "Spanish"]
                }
            ]
        }
    ];
    

    Result:

    Title: City Hunter.
    1: Original.
    Languages:
    Mandarin (City Hunter, Original)
    Cantonese (City Hunter, Original)
    
    2: DVD.
    Languages:
    French (City Hunter, DVD)
    Spanish (City Hunter, DVD) 
    

    In this example, the inner {{each}} is getting values from:

    • The outer {{each}} with ${edition.Name}
    • The root template data with ${$data.Name}