How to do looping in GSP?

Siva picture Siva · Nov 14, 2012 · Viewed 15k times · Source

I have GSP file in which i will be getting a value from the controller say for example ${paramsValue?.ruleCount} is 3 and based on that I have to create table rows.

Is there any way to do it in gsp

Answer

rdmueller picture rdmueller · Nov 14, 2012

what about

<g:each in="${(1..paramsValue?.ruleCount).toList()}" var="count" >
   ...
</g:each>

?

But it would be nicer if you would prepare a list with the content to be displayed in your controller...

Update:

just gave it a try:

<% def count=5 %>
<g:each in="${(1..count).toList()}" var="c" >
  ${c}
</g:each>

works.

<% def count=5 %>
<g:each in="${1..count}" var="c" >
  ${c}
</g:each>

works too and is even shorter.

Update2:

It seems that you want to use an URL parameter as count. This code will work in that case:

<g:each in="${params.count?1..(params.count as Integer):[]}" var="c" >
  ${c}
</g:each>

it will check if there is a count-parameter. If not, it will return an empty list to iterate over. If count is set, it will cast it to Integer, create a Range and implicitly convert it to a list to iterate over.