Tuesday, October 9, 2012

FreeMarker template with Spring Expression Language directives

FreeMarker provides a programmatic way to implement custom macro-style directives. The corresponding documentation is here.
Spring Expression Languale (SpEL) can be integrated into FreeMarker templates using custom directives.

At first, here is the template example with SpEL included:
<@spel/> is a FreeMarker custom directive with no body
{} is SpEL template prefix and postfix (standard #{} or ${} will not work because they interfere with FreeMarker internals)
@greetingBean is a Spring bean accessed inside the SpEL
name is a FreeMarker model variable

To implement custom directive one needs to implement FreeMarker interface TemplateDirectiveModel
Most of the code is the FreemarkerVariables class as a Map wrapper over FreeMarker variables, which is passed to SpEL expression as a root object.
SpEL expression itself can be defined in either parameter "expression" (as seen in greeting-template.ftl) or directly in <@spel>body as an expression</@spel>

SpelEvaluator is used for convenient SpEL initialization and evaluation, but the native SpelExpressionParser, StandardEvaluationContext, ParserContext, Expression, etc. can be used as well.

Here is simple test: and corresponding Spring context:

GreentingBean is simple bean to demostrate usage of both Spring beans and FreeMarker model variables in one SpEL expression {@greetingBean.printGreeting(name)} 

Maven dependencies:

Complete code can be fetched from SVN:
svn co http://adaptiweb.googlecode.com/svn/projects/blog/trunk/freemarker-spel-example/

No comments:

Post a Comment