Tuesday, December 28, 2010

Formatting Struts 2 s:checkboxlist tag

I recently had the need to format the struts 2 tag. By default it appears as a horizontal formatted list (checkBox1[] checkBox2[] checkBox3[] etc) but since the number of checkboxes were large, i wanted them to appear in a tabular format.

Here's what i did:
- After doing a quick Google search i figured that i needed to overwrite the default Freemarker template.
- All the templates are located in the struts-core.jar

1. Create a new directory structure at the root of my application called template/myapp and template/myapp_simple
2. The template we're looking for is checkboxlist.ftl. This is located in the struts-core.jar under templates/xhtml folder. We want to override that, so lets create our own version of it. To start with lets copy the existing freemarker templates (located in struts-core.jar templates/xhtml) into your new template/myapp folder.
3. Now edit the filer checkboxlist.ftl. As you can see its referring to the template stored under the simple folder.
<#include "/${parameters.templateDir}/simple/checkboxlist.ftl" />
Lets change that so that it points to your directory structure
<#include "/${parameters.templateDir}/myapp_simple/checkboxlist.ftl" />
4. Now lets copy the checkboxlist.ftl located in the template/simple folder (from the struts-core.jar) into your template/myapp_simple folder.
5. Lets override this file now. What i want to do is make all the checkboxes appear in a 4 column table. So here's what my checkboxlist.ftl looks like.


<#assign itemCount = 0/>
<#if parameters.list?exists>
<@s.iterator value="parameters.list">
<#assign itemCount = itemCount + 1/>
<#if parameters.listKey?exists>
<#assign itemKey = stack.findValue(parameters.listKey)/>
<#else>
<#assign itemKey = stack.findValue('top')/>

<#if parameters.listValue?exists>
<#assign itemValue = stack.findString(parameters.listValue)/>
<#else>
<#assign itemValue = stack.findString('top')/>

<#assign itemKeyStr=itemKey.toString() />
<#if itemCount%4=0>

<#elseif itemCount%4=2>

<#elseif itemCount%4=3>

<#else>


<#rt/>
<#if tag.contains(parameters.nameValue, itemKey)>
checked="checked"<#rt/>

<#if parameters.disabled?default(false)>
disabled="disabled"<#rt/>

<#if parameters.title?exists>
title="${parameters.title?html}"<#rt/>

<#include "/${parameters.templateDir}/simple/scripting-events.ftl" />
<#include "/${parameters.templateDir}/simple/common-attributes.ftl" />
/>

<#if itemCount%4=0>

<#else>



<#rt/>

<#else>


Thats it

1 comment:

sunandan said...

The ftl is not working.
Can you let me know exactly what is changed in the ftl.

thanks

Search This Blog