Get current index of for tag in jsrender

2019-09-11 14:13发布

问题:

Is there any way to get the current index of for tag in the tag.

Need an solution

{{for ~ID=#index}}
     {{:~ID}}
{{/for}}

It will not work because #index is accessible only within the for loop.

Working Code:

{{for}}
     {{:#index}}
{{/for}}

And is there any way to access the Jsonobject key and value in for tag instead of prop tag.

{{for arrayOfObj}}
   {{:#data.key}} //In here data is a jsonobject. 
   //I need an key and value of this object.
{{/for}}

Thanks in advance.

回答1:

Your question isn't very clear. You have an array of objects - OK so what do you want to do?

If you want to iterate over the array you can write {{for arrayOfObj}}...{{/for}}.

Now, inside that block you can get the index and the object. If you want to get a specific known key (if you know the object has a name property for example) you can write {{:name}}.

But if you want to iterate over all of the properties of each object, you can use {{props}} (for each object, within the {{for}} block):

{{for arrayOfObj}} - iterate over array
  {{:#index}} - this is the index in the array
  {{:name}}
  {{props}} - iterate over props of this object
    {{:key}}
    {{:prop}}
    {{:#getIndex()}} - this is the index in the array
  {{/props}}
{{/for}}