1. Shared variables
Freemarker's shared variables are one of my favorite "hidden" features. This feature allows you to set values that are automatically added to all templates. For example, you can set the name of the application as a shared variable.
12 |
Configuration configuration = new Configuration(); configuration.setSharedVariable( "app" , "StackHunter" ); |
Then access it like any other variable.
In the past, using shared variables generally referred to resource bundles and then used expressions like ${i18n.resourcebundle.key} to get values.
123 |
${i18n.countries.CA} ${i18n.countries[‘CA‘]} ${i18n.countries[countryCode]} |
The above lines refer to the value corresponding to the key "CA" within the Countries_en.properties resource bundle. You need to execute your own templatehashmodel and add it as a shared variable to achieve this goal.
2. Support JSON
Freemarker built-in JSON support. Let's say you have the following JSON stored in a string named user of the variable.
1 |
{ ‘firstName‘: ‘John‘, ‘lastName‘: ‘Smith‘, ‘age‘: 25, ‘address‘: { ‘streetAddress‘: ‘21 2nd Street‘, ‘city‘: ‘New York‘, ‘state‘: ‘NY‘, ‘postalCode‘: 10021 }} |
Use the? Eval to convert from a string to a JSON object and then use it in an expression just like any other data.
12 |
<#assign user = user?eval> User: ${user.firstName}, ${user.address.city} |
3. Class loading No PermGen issues
If you have developed a Java Web application for some time, you may not be unfamiliar with the PermGen problem with the JVM. Because Freemarker templates do not compile into classes, they do not occupy PermGen space and do not require a new classloader to load.
4. Macro definition (like JSP tags) very convenient
Comparison of Freemarker and JSP