Sunday, 21 June 2020

FreeMarker: #sep directive

#sep directive is used to print something between the items of a sequence (not before the first item or after the last item).

 

For example,

 

countryNames.ftl

<#list countryNames as countryName>${countryName}<#sep>, </#list>

Above snippet print country names like below.

India, Nepal, Sri Lanka, Germany

 

Step 1: 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 2: Define CountryNamesPopulator.

 

CountryNamesPopulator.java

package com.sample.app;

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

import com.sample.app.util.FreeMarkerUtil;

public class CountryNamesPopulator {
	public static void main(String args[]) throws Exception {
		List<String> countryNamesList = Arrays.asList("India", "Nepal", "Sri Lanka", "Germany");

		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("countryNames", countryNamesList);

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "countryNames.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

India, Nepal, Sri Lanka, Germany





Previous                                                    Next                                                    Home

FreeMarker: list or sequence slicing

Slicing is used to get the sub sequence.

 

For example, for the sequence ["A", "B", "C", "D", "E", "F"].

seq[1..*3] = AB

seq[1..<3] = AB

seq[1..*2] = BC

seq[1..] = BCDEF

 

Range Expression

Description

Example

start..end

Range from star number to end (inclusive)

seq[1..*3] = AB

 

start..<end or start..!end:

Range from start number to end (exclusive)

seq[1..<3] = AB

 

start..*length

Range from start to length number of items.

seq[1..*2] = BC

 

start..

Unbounded range.

seq[1..] = BCDEF

 

Find the below working application.

 

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

 

listSlicing.ftl
<#assign seq = ["A", "B", "C", "D", "E", "F"]>

seq : <#list seq as item>${item}</#list>

- seq[1..*3] : <#list seq[0..*2] as i>${i}</#list>
- seq[1..<3] : <#list seq[0..*2] as i>${i}</#list>
- seq[1..*2] : <#list seq[1..*2] as i>${i}</#list>
- seq[1..] : <#list seq[1..] as i>${i}</#list>

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 ListSlicingPopulator.

 

ListSlicingPopulator.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 ListSlicingPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "listSlicing.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

seq : ABCDEF

 

- seq[1..*3] : AB

- seq[1..<3] : AB

- seq[1..*2] : BC

- seq[1..] : BCDEF





Previous                                                    Next                                                    Home

FreeMarker: Concatenate lists or sequences

Using ‘+’ operator, you can concatenate lists or sequences.

 

Example

<#list ["Ram", "Rahim", "Joel"] + ["Krishna", "Abdul", "Chella"] + ["Sailu", "Mary"] as userName>

- ${userName}

</#list>

 

Find the below working application.

 

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

 

listConcatenation.ftl

<#list ["Ram", "Rahim", "Joel"] + ["Krishna", "Abdul", "Chella"] + ["Sailu", "Mary"] as userName>
- ${userName}
</#list>

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 ListConcatenationPopulator.

 

ListConcatenationPopulator.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 ListConcatenationPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "listConcatenation.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

- Ram

- Rahim

- Joel

- Krishna

- Abdul

- Chella

- Sailu

- Mary





Previous                                                    Next                                                    Home

FreeMarker: Items in the list are expressions

Items in the list are expression. So following snippet is completely valid.

 

<#list [2 + 2, 2 -2, "Foo"+"bar"] as item>

Value of element is : ${item}

</#list>

 

Find the below working application.

 

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

 

listExpressions.ftl
<#list [2 + 2, 2 -2, "Foo"+"bar"] as item>
Value of element is : ${item}
</#list>

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 ListExpressionPopulator.

 

ListExpressionPopulator.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 ListExpressionPopulator {
	public static void main(String args[]) throws Exception {

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

	}
}

Output

Value of element is : 4
Value of element is : 0
Value of element is : Foobar



Previous                                                    Next                                                    Home

Thursday, 18 June 2020

FreeMarker: Specify list elements in the template

Using [], we can specify list elements directly in the template.

 

listLiteral.ftl

<#list ["2", "3", "foo", 1.234] as x>
Value of element is : ${x}
</#list>

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;
	}

}

Define ‘ListLiteralPoplator.java’.

 

ListLiteralPoplator.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 ListLiteralPoplator {
	public static void main(String args[]) throws Exception {

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

	}
}

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

Value of element is : 2
Value of element is : 3
Value of element is : foo
Value of element is : 1.234

As you see above example, list is heterogeneous in Freemarker and it can handle different types of values.




Previous                                                    Next                                                    Home

Wednesday, 17 June 2020

FreeMarker: #list directive

#list directive is used to list the collection of elements.

 

Syntax

<#list sequence as item>

    Part repeated for each item

</#list>

 

employees.ftl

Id   		first_name  	last_name
-------------------------------------------
<#list employees as employee>
${employee.id} 	 	${employee.firstName}		${employee.lastName}
</#list>

Step 1: Define Employee class.

 

Employee.java

package com.sample.app.templates.model;

public class Employee {
	private int id;
	private String firstName;
	private String lastName;

	public Employee(int id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

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 EmployeePopulator.

 

EmployeePopulator.java

package com.sample.app;

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

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

public class EmployeesPopulator {
	public static void main(String args[]) throws Exception {
		Employee emp1 = new Employee(1, "Krishna", "Gurram");
		Employee emp2 = new Employee(2, "Ram", "Kota");
		Employee emp3 = new Employee(3, "Gopi", "Battu");
		Employee emp4 = new Employee(4, "Joel", "Chelli");

		List<Employee> empList = Arrays.asList(emp1, emp2, emp3, emp4);

		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("employees", empList);

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "employees.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

Id   		first_name  	last_name
-------------------------------------------
1 	 	Krishna		Gurram
2 	 	Ram		Kota
3 	 	Gopi		Battu
4 	 	Joel		Chelli


Previous                                                    Next                                                    Home

Monday, 15 June 2020

FreeMarker: elseif directive

We can define multiple conditional checks using if-elseif-else directive.

 

Syntax

<#if condition>

  ...

<#elseif condition2>

  ...

<#elseif condition3>

  ...

...

<#else>

  ...

</#if>

 

studentGrades.ftl
<#if marks < 35 >
  	You are failed
<#elseif marks < 50>
	You are passed and got third class
<#elseif marks < 60>
	You are passed and got second class
<#elseif marks < 70>
	You are passed and got first class
<#else>
    You are passed and got distinction
</#if>

Step 1: 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 2: Define StudentGradePopulator.

 

StudentGradePopulator.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 StudentGradePopulator {
	public static void main(String args[]) throws Exception {
		Map<String, Object> modelObject = new HashMap<String, Object>();

		modelObject.put("marks", 30);

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
		System.out.println(stringWriter.toString().trim());
		
		modelObject.put("marks", 50);
		stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
		System.out.println(stringWriter.toString().trim());
		
		modelObject.put("marks", 70);
		stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
		System.out.println(stringWriter.toString().trim());
		
		modelObject.put("marks", 80);
		stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
		System.out.println(stringWriter.toString().trim());
		
	}

}

Output

You are failed

You are passed and got second class

You are passed and got distinction

You are passed and got distinction




Previous                                                    Next                                                    Home