Search code examples
loopsspark-view-engine

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

  • 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.