Monday, August 17, 2009

A single form checkbox macro for Freemarker and Spring

If you want to use Freemarker in your SpringMVC project, Spring comes with a limited amount of macros in the file spring.ftl.

One macro noteworthy for its absence is a macro to display a single checkbox. I've seen various snippets of example code around the web on how to do this, but all of them seemed to be deficient in either error handling or binding. Here's a macro that works!

<#macro formCheckbox path attributes="">
<@spring.bind path />
<input type="hidden" name="_${spring.status.expression}" value="false"/>
<input type="checkbox" id="${spring.status.expression}" name="${spring.status.expression}"
<#if spring.status.value?? && spring.status.value?string=="true">checked="true"</#if>
${attributes}
<@spring.closeTag/>
</#macro>

0 comments: