Saturday, October 10, 2009

Development Using FreeMarker

If you are developing your application using freemarker, it is necessary for you to learn its syntax - to create FM templates.

I have faced some issues while building templates using FM and also learned the right way to use freemarker syntax.

Following are some points that I have go through while using freemarker:

Passing Beans to Templates instead of Lists:

In my case it is suitable for be to create a Java Bean and pass its object to templates. I was sending my data in the form of Lists previously but it is causing some problems as well as making things complex.

The structure in which the data is stored in the list is the biggest issue. What I have to do is to create a menu that can have n-numbers of sub-menus and each sub-menu can have n-numbers of their sub-menus. Getting really mixed up using lists. Now I have created a bean to handle my menus. Bean looks like as follows:



class MenuBean {

String title;
String url;
List children;
etc..
}



If condition and null object identification:

To handle conditional statements it is quite easy in freemarker. The "IF" condition can easily be applied any where with <#if> clause. One thing to remember here is that the closing tags are must for most of freemarker tags. So when the conditional tag ends also has to placed. Just like brackets open and closed.

Identification of empty list or null can also if done by <#if> tag. The syntax is a bit cheeky but it works. The statement "<#if yourList??>" verifies that their exists some element inside "yourList" and is not null, so it enter into the condition.


foreach tag:

Iterating through a list can also be done in freemarker. A simple <#foreach> tag is provided to iterate a list.

The sytax for foreach tag is also simple:

<#foreach element in yourList>


Here element is just an alias of your list that can be used to access the properties or values inside youList.

yourList is the name of list.


list tag:

List tag is also used to iterate any list. It can also be used as a "for loop".

To iterate a list using <#list> following syntax is used:

<#list yourList as x>


If you want to used <#list> to work as a for loop, you have to use it as follows:

<#list 1..10 as x>


The <#list> will loop from 1 to 10 and ends.


Click this Link for FreeMarker #Functions and #Macros


rizzz86

No comments: