user1577161 user1577161 - 1 year ago 117
HTML Question

Using Grails to output data in columns

Given a variable amount of data, I want to create a table with fixed number of columns per row. For example, I may only want four columns per row:

<table>
<tr>
<th>COLUMN_1</th> <th>COLUMN_2</th> <th>COLUMN_3</th> <th>COLUMN_4</th>
</tr>

<tr>
for(-some code here-) {
<td>-some output from the loop-</td>
}
</tr>
</table>


But as you can see, if the data consisted of 10 elements, the table row will exceed my four columns.

How can I output the data so the number of columns is constant and new rows are created as needed?

Answer Source

One of the great things about Grails (and Groovy) is its extensibility. Too often developers constrain their thinking to what their tools and frameworks currently provide. I often find it helps to think about what an ideal, more elegant solution would be if it were to be built-in to the framework. That usually gives me a good direction for how I want to implement it. In your scenario, I would prefer a GSP tag that iterates over a collection in groups of elements, so that you can process each group of elements. Something like the following:

<table>
<lm:eachGroup size="4" var="row" in="${myCollection}">
   <tr>
   <g:each var="cell" in="${row}">
      <td>${cell}</td>
   </g:each>
   </tr>
</lm:eachGroup>
</table>

Of course, that doesn't exist... so I created it! It could be improved by providing a flag to pad the last group of elements so you get a complete row, but I'll leave that as an exercise for the reader. ;-)

To use my <lm:eachGroup> from my taglib in your project you can clone the git repository for my Grails plugin:

$ git clone https://github.com/erturne/leapingmindtaglib

Package the plugin:

$ grails package-plugin

Then install it into your app.

BTW, I did something similar a while back to add an eachGroup() method to List.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download