Get count of items in a velocity list

Tom picture Tom · Aug 17, 2012 · Viewed 12.3k times · Source

I'm creating a set of custom templates and structures for a Liferay site.

One structure provides for a repeatable section, which its matching template then iterates over.

However, for styling reasons, I need to know how many instances of the repeatable section are actually present, and I need to know before I loop.

So, the template code is something like this:

#foreach($thisChunk in $chunk.getSiblings())
    [emit some HTML]
#end

I want to do some conditional logic before the foreach, and emit a different CSS classname on the containing element depending on how many $chunks there are.

Any ideas how to access the number of siblings without looping through them first?

Answer

Olaf Kock picture Olaf Kock · Aug 17, 2012

Easy: $chunk.getSiblings().size()

How to find out? It's a plain old Java object (java.util.ArrayList in my quick test). You can find this out when you just temporarily debug your template with $chunk.getSiblings().getClass().getName() and then continue with the interface of that class.