Monday, 15 June 2020

Free Marker: #else directive

Using #else directive, we can specify what to do when the condition in #if directive is evaluated to false.

 

Syntax

<#if condition>

  ...

<#else>

  ...

</#if>

 

welcome.ftl

<#if user.gender == "Male">
  Welcome Mr. ${user.name}
<#else>
  Welcome Madam.  ${user.name}
</#if>

Step 1: Define Model class ‘WelcomeUser’.

 

WelcomeUser.java

package com.sample.app.templates.model;

public class WelcomeUser {
	private String name;
	private String gender;

	public WelcomeUser(String user, String gender) {
		super();
		this.name = user;
		this.gender = gender;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

Step 2: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define ‘WelcomeUserPopulator’.

 

WelcomeUserPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.templates.model.WelcomeUser;
import com.sample.app.util.FreeMarkerUtil;

public class WelcomeUserPopulator {
	public static void main(String args[]) throws Exception {
		Map<String, Object> modelObject = new HashMap<String, Object>();

		modelObject.put("user", new WelcomeUser("Krishna", "Male"));

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "welcome.ftl");
		System.out.println(stringWriter.toString().trim());
		
		modelObject.put("user", new WelcomeUser("Sailu", "Female"));
		stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "greet.ftl");
		System.out.println(stringWriter.toString().trim());
	}
}

Output

Welcome Mr. Krishna

Welcome  Madam. Sailu



Previous                                                    Next                                                    Home

Sunday, 14 June 2020

FreeMarker: if directive

Using if directive, you can conditionally skip some section of the template.

 

Syntax

<#if condition>

  ...

  ...

</#if>

 

For example, I would like to greet user with Mr. if user is Male and Madam, if user is female.

 

greet.ftl

Welcome <#if user.gender == "Male">Mr.</#if> <#if user.gender == "Female">Madam.</#if> ${user.name}

In the above example, user.gender in the #if directive is a variable. In general unquoted words inside directives or interpolations are treated as references to variables.

 

== operator is used to check the value on left hand side is equal to right hand side or not. != is used to check for inequality.

 

Step 1: Define model class GreetUser.

 

GreetUser.java

package com.sample.app.templates.model;

public class GreetUser {
	private String name;
	private String gender;

	public GreetUser(String user, String gender) {
		super();
		this.name = user;
		this.gender = gender;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

Step 2: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define GreetUserPopulator.java

 

GreetUserPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.templates.model.GreetUser;
import com.sample.app.util.FreeMarkerUtil;

public class GreetUserPopulator {
	public static void main(String args[]) throws Exception {
		Map<String, Object> modelObject = new HashMap<String, Object>();

		modelObject.put("user", new GreetUser("Krishna", "Male"));

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "greet.ftl");
		System.out.println(stringWriter);
		
		modelObject.put("user", new GreetUser("Sailu", "Female"));
		stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "greet.ftl");
		System.out.println(stringWriter);
	}

}

Output

Welcome Mr.  Krishna

Welcome  Madam. Sailu




Previous                                                    Next                                                    Home

FreeMarker: Directives

FTL tags are used to call directives. For example, we can define id directive like below.

 

Example

<#if user.gender == "Male">

  ...

  ...

</#if>

 

There are two kinds of FTL tags used to compose ‘if’ directive.

 

a.   Start-tag: <#directivename parameters>

b.   End-tag: </#directivename>

 

Not all the directives required to have 'end' tag. For example, ‘include’ directive do not have any content, so it does not have any end tag.

 

Example

<#include something>

 

Types of Directives

Freemarker has two kinds of directives.

a.   Predefined Directive: Directives defined by FreeMarker. Example: if, list, include

b.   Userdefined Directive: Directives that are defined by user.



Previous                                                    Next                                                    Home

FreeMarker: Raw String Literals

In Raw string literals ${, backslash do not have any specific meaning.

 

How to define raw literal?

Just put an r directly before the opening quotation mark or apostrophe-quote.

 

Example:

${r"C:\foo\bar\tab\n"}

 

Step 1: Define rawLiteral.ftl file under src/main/resources/templates folder.

 

rawLiteral.ftl

${r"C:\foo\bar\tab\n"}

 

Step 2: Define ‘FreeMarkerUtil’ class that takes model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define RawLiteralPopulator.

 

RawLiteralPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class RawLiteralPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "rawLiteral.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Run the application, you will see below messages in the console.

 

C:\foo\bar\tab\n



Previous                                                    Next                                                    Home

FreeMarker: Escaping Sequences

An escape sequence is a sequence of characters that doesn't represent itself when used inside string literal or character. It is composed of two or more characters starting with backslash \.

 

For example:

\n represents new line.

\t represents tab

 

Example 1: Below statement use \n

Hello ${"How are you? \nI am fine, Thank you."}

 

Example 2: Below statement prints the string 'quoted' in double-quotes.

${"It's \"quoted\" and this is a backslash: \\"}

 

Below table summarizes the escape sequences supported by FreeMarker.

 

Escape Sequence

Description

\"     

Quotation mark (u0022)

\'

Apostrophe (a.k.a. apostrophe-quote) (u0027)

\{     

Opening curly brace: {

\=    

Equals character: =

\\     

Back slash (u005C)

\n

Line feed (u000A)

\r     

Carriage return (u000D)

\t      

Horizontal tabulation (a.k.a. tab) (u0009)

\b     

Backspace (u0008)

\f      

Form feed (u000C)

\l      

Less-than sign: <

\g     

Greater-than sign: >

\a     

Ampersand: &

\xCode      

 

Character given with its hexadecimal Unicode code (UCS code). The Code after x represents 1 to 4 hexadecimal digits.

 

Example

"\xA9 1999-2001",

"\x0A9 1999-2001",

"\x00A9 1999-2001"

 

Find the below working application.

 

Step 1: Define ‘escapeSequence.ftl’ file under src/main/resources/templates folder.

 

escapeSequence.ftl
Hello ${"How are you? \nI am fine, Thank you."}

${"It's \"quoted\" and this is a backslash: \\"}

Step 2: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define EscapeSequencePopulator.

 

EscapeSequencePopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class EscapeSequencePopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "escapeSequence.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Run the application, you will see below messages in console.

Hello How are you? 
I am fine, Thank you.

It's "quoted" and this is a backslash: \



Previous                                                    Next                                                    Home

FreeMarker: Comments

Comments are used to document your ftl file. Comments are delimited <#-- and -->

 

user.ftl
<#-- User details -->
name: ${user.name}
age: ${user.age}
city: ${user.city}

Previous                                                    Next                                                    Home

Friday, 12 June 2020

FreeMarker: Basic Building Blocks

There are 3 basic building blocks in FreeMarker.

 

Interpolations

Interpolations are represented by ${…}, FreeMarker will replace it with the actual value coming from the model object.

 

FreeMarker Template tags

These are instructions given to FreeMarker. Built-in template tags start with # and User defined tags start with @.

 

Example Of Built-in Tags

#if, #else, #list

 

Comments

Comments are used to document your ftl file. Comments are delimited <#-- and -->



Previous                                                    Next                                                    Home