Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop with in the jsrender template

In my working scenario i am using the following code snippet with in the js render template:

{{:#data['" + columnName + "']}} 

and this will return the value as:

[object Object],[object Object]

How to get a specific property from this array object [object Object],[object Object] within the js render template using a for loop?

like image 474
Raja Avatar asked Jan 09 '14 05:01

Raja


3 Answers

You can use {{for}} to iterate over an array. Something like this:

<ul>
{{for columnName}}
  <li>{{:Property}}</li>
{{/for}}
</ul>

Inside the loop, your base scope automatically becomes that particular object in the array, so you can output any of the object's properties directly with {{:Property}}.

like image 172
Dave Ward Avatar answered Nov 20 '22 21:11

Dave Ward


I have given example to demonstrate how jsrender for loop and props working. StudentList has array of student details and to iterate loop on Student list you have to just use {{for StudentList}}{{/for}}.

Now each student have three property, so iterate through property you can use {{props}}{{/props}} tag and to render data use {{>key}} and {{>prop}}

Doc: https://www.jsviews.com/#propstag

JSON data:

<!-- language: lang-json -->

"StudentList": [
        {
            "RollNo": 1,
            "Name": "John Doe",
            "Subject": "Maths"            
        },
        {
            "RollNo": 2,
            "Name": "Jane Doe",
            "Subject": "Physics"            
        },
        ...

Render Template:

<!-- language: lang-html -->

{{for StudentList}}
    <tr>
        {{props #data}}
            <td>{{>key}}</td><td>{{>prop}}</td>
        {{/props}}
    </tr>
{{/for}}   
like image 35
Mohnish Karhade Avatar answered Nov 20 '22 21:11

Mohnish Karhade


For iterating over an array, see http://www.jsviews.com/#fortag. (Lower in the page shows the use of the tag for looping over an array).

Also, some comments about your template example:

It looks like you are using a generated template, with the value of the columnName parameter inserted. So if columnName has the value "fooColumn" your template snippet is {{:#data['fooColumn']}} - which is actually equivalent to {{:#data.fooColumn}}, which can be further simplified to {{:fooColumn}}.

(I assume the value of columnName is a valid JavasScript name - not some value like "foo column", say, with white space - in which case your syntax would indeed be appropriate.)

Now, if #data.fooColumn is an array of objects each of which has a 'itemProperty' property, then using {{for}} to iterate over the array looks like this (slight change on David Ward's example):

<ul>
  {{for fooColumn}}
    <li>{{:itemProperty}}</li>
  {{/for}}
</ul>

The generated form of that using columnName would be

"<ul>{{for " + columnName + "}}<li>{{:itemProperty}}</li>{{/for}}</ul>"
like image 40
BorisMoore Avatar answered Nov 20 '22 22:11

BorisMoore