User Tools

Site Tools


techniques:counters

Counters

Use this technique to associate a counter with each element in a list.

Assume you have the following model:

<pages>
    <page  name="Color"  />
    <page  name="Length" />
    <page  name="Time"   />
</pages>

and you want to add an index number, starting at 7, to each page element to get something like this:

<pages>
    <page  name="Color"  index="7"   />
    <page  name="Length" index="8"   />
    <page  name="Time"   index="9"   />
</pages>

You can use something like the following tag block to accomplish this task:

<c:setVariable select="6" var="counter" />

<c:iterate  select="\pages\page" var="p" >

    <c:setVariable select="1 + $counter" var="counter" />
 
    <c:set select="$p" name="index"><c:get select="$counter" /></c:set>

</c:iterate>

Note that since the model is being updated, best practices would recommend that this bit of template logic be performed in the main.prod template or one of the templates included by main.prod. The logic will, of course, work in templates that generate file content, but the white space inside and around the tags will be output as well.

techniques/counters.txt · Last modified: 2016/07/10 17:34 by chrisgerken