简体   繁体   中英

Cannot loop through multidimensional array with handlebars

Looking at my data that is coming through:

data: {
    content: [
    [
    "School Name",
    "Location",
    "Type",
    "No. eligible pupils",
    "Average points per student",
    "Average points per exam entry",
    "% obtaining two facilitating subjects"
    ],
    [
    "Colchester Royal Grammar School",
    "Colchester",
    "State",
    "349",
    "1428",
    "263.3",
    "77%"
    ], and so on...
 ]
}

I am trying to loop through this array of arrays, to create a table. So for each array I would need to wrap it in <tr></tr> and for each element inside every array I need it wrapped in a <td></td> . I will need to differentiate the first row to use <thead> and <th> as well but at the moment I am trying to get my head around the proper structure.

What my code does is create only one <td> containing the whole thing, rather than multiple <tr> s or <td> s.

        {{#each data.content}}

            <tr>

                {{#each this}}
                    <td>{{ this }}</td>
                {{/each}}

            </tr>

        {{/each}}

you cannot directly use data inside your template.because you are passing data object to compiled template function.so you should use this to refer current context.

better use block parameters to avoid more number of this reference.which will make the code less understandable

without block parameters

{{#each this.content}} 
     <tr>
        {{#each this}} 
            <td>{{ this }}</td> 
        {{/each}} 
     </tr>
 {{/each}}

by using block parameters,

{{#each this.content as | rowKey, row |}} 
         <tr>
            {{#each row as | colKey, column|}} 
                <td>{{ column }}</td> 
            {{/each}} 
         </tr>
 {{/each}}

it has more advantages when the template grows bigger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM