Freemarker templates over Velocity

We have used templates over JSP for many years. The templates are used in our mail sending library, HTML pages in the pure java program, web application or in the Spring container. Velocity was our first choice due to its simplicity and ease of use. However, while our template files become more complex, we face many issues with Velocity’s usage in MyCollab. We evaluated several template libraries and finally Freemarker is a tool we choose to invest time for integrating. Below are what Freemarker offers that Velocity does not have the same features:

  • Velocity does not support the for loop iteration: For the complex templates, we need to add several programming logics to the template
  • Velocity does not have powerful built-in method: Freemarker has a lot of useful built-in methods for collections, maps, scalar etc
  • Velocity does not support the multi languages templates, in include directive or the pure template. It made us add the extra layer to detect the associated template with locale by ourselves. Freemarker supports the locales in their core otherwise.

Other important factors are Velocity seems to be discontinued for 6 years, the latest binaries of Velocity engine is from more than 5,5 years. However, we do not have any issue with the latest Velocity engine, it does like what it advertise but the discontinued development prevents us from getting the more features that we may need.

Migrating from Velocity to Freemarker did not take much time from our development team. Their syntaxes are nearly similar while we learned and used Freemarker built-in methods. We also reduce the length of template files by using macros, and other Freemarker templates. The result is quite expressive though the end user does not recognize the change because they only receive the HTML content 🙂

To use Freemarker in your Java program, you need to initialize the Configuration instance

If you are using the Freemarker in the Spring container, you can create a new bean

Because the creation of Configuration instance is time-consuming, you should create a singleton instance and use across the application. In our case, we use a global variable while we use in and outside Spring container.

Then we gather the model variables, fill in template and receive the output result

The writer instance keeps the output of template after the processing phase. To support multi languages template, you can use the method configuration.getTemplate(String, Locale) instead of configuration.getTemplate(String)

Leave a Reply

Your email address will not be published. Required fields are marked *