Nested eachs in jQuery template

僤鯓⒐⒋嵵緔 提交于 2020-01-24 15:01:10

问题


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.


回答1:


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}


来源:https://stackoverflow.com/questions/8508404/nested-eachs-in-jquery-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!