'increment variable value in spark view engine

I try to go through a for each loop and increment value of variable to name my label with below code

<set i="0"/>
<div each="var x in Model">

<input name='field-${i}' value='${x.Id}'/>

<set i=i+1 />
</div>

but it did not increment the value of 'i' , how can I increment the value of i in above loop

thanks



Solution 1:[1]

The best way to do this is to use the built in indexer that Spark creates in a for loop. The above could be written like this:

<div each="var item in Model">
   <input name='field-${itemIndex}' value='${item.Id}'/>
</div>

Even shorter than the original, and no need to track variables yourself. Also, no need to specifically use item, in your case it would be xIndex because x was your instance.

Solution 2:[2]

With slight modification:

<var i="0"/>
<div each="var x in Model">
    <input name='field-${i}' value='${x.Id}'/>
    <set i="i+1" />
</div>

this should work.

The initial 'set' has been changed to 'var' and quotes were added around i+1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer
Solution 2 super_dummy