Accessing the Loop Index and Number of Items

We've added a variety of new WebvantaScript statements to make it easier to provide specialized displays of database content by accessing the loop index in various ways. This article describes each of the new statements.

Accessing the Loop Index

w:each_index

For use inside an "each" iterator, such as w:kb:item:each or w:taxonomy:each; returns the number of the current index, starting at 0 for the first iteration.

This example lists all the articles and labels them with sequential numbers:


<ul>

  <w:kb:item:each type='articles'>

    <li>Article #<w:each_index />: <w:name /></li>

  </w:kb:item:each>

</ul>

Testing the Loop Index

w:if_each_index condition="operator number"

"operator" is a standard conditional comparison, such as ==, >, <, !=

This example adds a dividing line after the first five items:


<ul>

  <w:kb:item:each type='articles'>

    <li>Article #<w:each_index />: <w:name /></li>

    <w:if_each_index condition="== 5">

      <hr />

    </w:if_each_index>

  </w:kb:item:each>

</ul>

Note: as with all "if" WebvantaScript statements, the "unless" form is also available.

Finding the Number of Items

w:kb:item:iterator_size

Returns the total size of the current iterator's items count, after any conditions are applied.

This example displays "Article #x of y" where y is the total number of articles about dogs.


<ul>

  <w:kb:item:each type='articles' taxonomy='animals:dogs'>

    <li>Article #<w:each_index /> of <w:kb:item:iterator_size />: <w:name /></li>

  </w:kb:item:each>

</ul>

(This assumes there is a taxonomy "animals" that has a term "dogs".)

w:kb:item:iterator_preflight_size

Use the same type, condition, and taxonomy attributes as item:each. Returns how many would match if the iterator was executed; much faster than actually iterating through all the items.

This example shows the number of articles about dogs without iterating through them:

There are <w:kb:item:iterator_preflight_size type='articles' taxonomy='animals:dogs' /> articles about dogs.

Testing the Number of Items

w:kb:item:if_iterator_preflight_size

Use the same type, condition, and taxonomy attributes as item:each, plus a count attribute. The code inside the IF block will be executed only if the number of items returned by the interator_preflight_size is greater than the value in "count".

For example, if there are more than 10 articles about dogs:


<w:kb:item:if_iterator_preflight_size type='articles' taxonomy='animals:dogs' count='10'>

  This site has more than 10 articles about dogs!

</w:kb:item:if_iterator_preflight_size>

Note: as with all "if" WebvantaScript statements, the "unless" form is also available.