Thursday, July 19, 2007

Using Grails GSP to provide alternating colors in a table

Using Grails GSP to provide alternating colors in a table

I saw something related to this a while ago on the net but was not able to find it again. So I just came up with my own approach.

I wanted a table that had alternating rows highlighted. There are many ways to approach this. This solution is what I am going to use since it all falls on the view side of things and as such is rather easy to code. It is based on the code examples from

<table width="50%" align="right" border="0" cellpaddinng="0" cellspacing="0">
<g:def var="counter" value="${1}" />

<g:each in="${lastElement}">


<td style="background:
${counter % 2 == 0 ? 'white' : 'grey'">
<g:showElementResults id='${}'/>



<g:set var="counter" value="${counter + 1}" />



It is the "${counter % 2 == 0 ? 'white' : 'grey'}" that does all the work. The only other interesting elements are in bold. Simply change the two colors to get the banding effect you want. A more advanced version of this could set a style name or some other CSS element to improve the approach. I am sure there are several ways to do this. This seems to work for me. The "<g:showElementResults id='${}'/>" code is not relevant here. It's just a taglib I use to create the formatted text of the cell based on an id and the rest is the just the <g:each> tag boilerplate.

No comments: