Sunday, 5 July 2020

FreeMarker: StringTemplteLoader: Load templates from strings

‘StringTemplateLoader’ uses a Map with String-s as its source of templates.

 

Follow the below step-by-step procedure to process a template using StringTemplateLoader.

 

Step 1: Define templates.

String copyRightTemplate = "---------------------------------------------------------------------------------\n"
        + "All these examples are owned by https://self-learning-java-tutorial.blogspot.com/\n"
        + "You can use these examples and share to others also\n" + "\n" + "Author: Krishna\n"
        + "Date: ${today?datetime}\n"
        + "---------------------------------------------------------------------------------";

String welcomeTemplate = "<#-- Include Demo -->\n" + "\n" + "<#include \"/copyright\">\n" + "\n"
        + "Hello ${name}, Welcome to our Application.";

Step 2: Load the templates to StringTemplateLoader.

StringTemplateLoader stringLoader = new StringTemplateLoader();

stringLoader.putTemplate("copyright", copyRightTemplate);

stringLoader.putTemplate("welcomeTemplate", welcomeTemplate);

 

Step 3: Get the instance of Configuration and set the template loader.

Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);

configuration.setTemplateLoader(stringLoader);

 

Step 4: Define Root Object.

 

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

 

rootObject.put("today", new Date());

rootObject.put("name", "Krishna");

 

Step 5: Get the template.

Template template = configuration.getTemplate("welcomeTemplate");

 

Step 6: Process the template using rootObject.

StringWriter stringWriter = new StringWriter();

template.process(rootObject, stringWriter);

 

Find the below working application.

StringTemplateLoaderDemo.java

package com.sample.app;

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

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

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

        String copyRightTemplate = "---------------------------------------------------------------------------------\n"
                + "All these examples are owned by https://self-learning-java-tutorial.blogspot.com/\n"
                + "You can use these examples and share to others also\n" + "\n" + "Author: Krishna\n"
                + "Date: ${today?datetime}\n"
                + "---------------------------------------------------------------------------------";

        String welcomeTemplate = "<#-- Include Demo -->\n" + "\n" + "<#include \"/copyright\">\n" + "\n"
                + "Hello ${name}, Welcome to our Application.";

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("copyright", copyRightTemplate);
        stringLoader.putTemplate("welcomeTemplate", welcomeTemplate);

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setTemplateLoader(stringLoader);

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

        rootObject.put("today", new Date());
        rootObject.put("name", "Krishna");

        Template template = configuration.getTemplate("welcomeTemplate");

        StringWriter stringWriter = new StringWriter();
        template.process(rootObject, stringWriter);

        System.out.println(stringWriter.toString());

    }
}

Output

---------------------------------------------------------------------------------
All these examples are owned by https://self-learning-java-tutorial.blogspot.com/
You can use these examples and share to others also

Author: Krishna
Date: 24 May, 2020 12:43:14 AM
---------------------------------------------------------------------------------
Hello Krishna, Welcome to our Application.



Previous                                                    Next                                                    Home

FreeMarker: Load the template from a string

In this post, I am going to explain how to load template from a string and merge it with data model.

 

Step 1: Define the template string.

String userDetailsTemplate = "<#-- User details -->\n" + "name: ${user.name}\n" + "age: ${user.age}\n" + "city: ${user.city}";

 

Step 2: Define instance of the template.

Template template = new Template("My_template", new StringReader(userDetailsTemplate), new Configuration(Configuration.VERSION_2_3_30));

 

Step 3: Define model object.

User user = new User("Krishna", 29, "Bangalore");

 

Step 4: Define root object.

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

rootObject.put("user", user);

 

Step 5: Process the template with rootObject.

StringWriter stringWriter = new StringWriter();

template.process(rootObject, stringWriter);

 

Find the below working application.

 

LoadDataFromString.java
package com.sample.app;

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

import com.sample.app.templates.model.User;

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

public class LoadDataFromString {

  public static void main(String args[]) throws Exception {
    String userDetailsTemplate = "<#-- User details -->\n" + "name: ${user.name}\n" + "age: ${user.age}\n"
        + "city: ${user.city}";

    Template template = new Template("My_template", new StringReader(userDetailsTemplate),
        new Configuration(Configuration.VERSION_2_3_30));

    User user = new User("Krishna", 29, "Bangalore");

    Map<String, Object> rootObject = new HashMap<>();
    rootObject.put("user", user);

    StringWriter stringWriter = new StringWriter();
    template.process(rootObject, stringWriter);

    System.out.println(stringWriter.toString());

  }

}

Output

name: Krishna

age: 29

city: Bangalore

 

One drawback of this approach is if you want to create templates from strings that import other templates this method doesn't work. You can solve this problem by using StringTemplateLoader.





Previous                                                    Next                                                    Home

Saturday, 4 July 2020

FreeMarker: String slicing

FreeMarker supports string slicing.

 

For example,

s = "ABCDEFGHIJ"

 

${s[2..5]} =  CDEF

${s[2..<5]} =  CDE

${s[2..*3]} =  CDE

${s[2..*100]} =  CDEFGHIJ

${s[2..]} =  CDEFGHIJ

 

 

Below table specifies different ways to specify ranges.

 

Range Expression

Description

Example

start..end

Range from star number to end (inclusive)

For a string s = "ABCDEFGHIJ", s[2..5] return CDEF.

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

Range from start number to end (exclusive)

For a string s = "ABCDEFGHIJ", s[2..<5] return CDE.

start..*length

Range from start to length number of items.

For a string s = "ABCDEFGHIJ", s[2..*3] return CDE.

start..

Unbounded range.

For a string s = "ABCDEFGHIJ", s[2..] return CDEFGHIJ.

 

Find the below working application.

 

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

 

stringSlice.ftl
<#assign s = "ABCDEFGHIJ">

s = ${s}
${r"${s[2..5]} = "} ${s[2..5]}
${r"${s[2..<5]} = "} ${s[2..<5]}
${r"${s[2..*5]} = "} ${s[2..*5]}
${r"${s[2..*100]} = "} ${s[2..*100]}
${r"${s[2..]} = "} ${s[2..]}

Step 2: Define ‘FreeMarkerUtil’ class that takes model object 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 StringSlicePopulator.

 

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

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

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

	}
}

Output

s = ABCDEFGHIJ
${s[2..5]} =  CDEF
${s[2..<5]} =  CDE
${s[2..*5]} =  CDEFG
${s[2..*100]} =  CDEFGHIJ
${s[2..]} =  CDEFGHIJ



Previous                                                    Next                                                    Home

FreeMarker: Access a character in string using index notation

You can access the individual character of a string using index notation.

 

Example

<#assign data="Hello World" >

 

data[0] return the character at index 0 which is ‘H’.

data[1] return the character at index 1 which is ‘e’.

 

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

 

stringIndexNotation.ftl
<#assign data="Hello World" >

Value at 0th index ${data[0]}
Value at 1st index ${data[1]}
Value at 2nd index ${data[2]}
Value at 3rd index ${data[3]}
Value at 4th index ${data[4]}

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 StringIndexNotationPopulator.

 

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

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

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

	}
}

Output

Value at 0th index H
Value at 1st index e
Value at 2nd index l
Value at 3rd index l
Value at 4th index o

Previous                                                    Next                                                    Home

Friday, 3 July 2020

FreeMarker: String concatenation

Using ‘+’ operator, you can concatenate strings.

 

Example

<#assign str1="Foo" >

<#assign str2="Bar" >

<#assign str3="Fin" >

 

<#assign result = str1 + "," + str2 + "," + str3>

 

Find the below working application.

 

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

 

stringConctenation.ftl
<#assign str1="Foo" >
<#assign str2="Bar" >
<#assign str3="Fin" >

<#assign result = str1 + "," + str2 + "," + str3>

Value Of str1 is : ${str1}
Value Of str2 is : ${str2}
Value Of str3 is : ${str3}
Value Of result is : ${result}

Step 2: Define ‘FreeMarkerUtil’ class that takes model object 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 StringConcatenationPopulator.

 

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

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

	}
}

Output

Value Of str1 is : Foo
Value Of str2 is : Bar
Value Of str3 is : Fin
Value Of result is : Foo,Bar,Fin

Previous                                                    Next                                                    Home

FreeMarker: Working with Strings


Previous                                                    Next                                                    Home

FreeMakrer: assign Directive: Define variables

‘assign’ directive is used to define variables.

 

Syntax

<#assign name1=value1 name2=value2 ... nameN=valueN>

 

Naming conventions

a.   Variable name can only contain letters, digits, underline (_), dollar ($), at-sign (@).

b.   First character of a variable name can't be an ASCII digit (0-9).

c.    Variable name can also contain minus (-), dot (.), and colon (:)

 

Example

<#assign empDetails={ "id" : 1, "name": "krishna", "city": "Bangalore" } >

<#assign items = [1, 2, 3, 4]>

<#assign a=10, b=11, name="Krishna">

 

Find the below working application.

 

Step 1: Create assignDirective.ftl file under src/main/resources/templates folder.

 

assignDirective.ftl
<#assign empDetails={ "id" : 1, "name": "krishna", "city": "Bangalore" } >

<#list empDetails as key, value> 
${key} = ${value} 
</#list>


<#assign items = [1, 2, 3, 4]>
<#list items as item> 
Value of item is ${item}
</#list>

<#assign a=10, b=11, name="Krishna">

Value of a is ${a}
Value of b is ${b}
Value of name is ${name}

Step 2: Define ‘FreeMarkerUtil’ class that takes model object 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 AssignDirectivePopulator.

 

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

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

	}
}

Output

id = 1 
name = krishna 
city = Bangalore 


Value of item is 1
Value of item is 2
Value of item is 3
Value of item is 4


Value of a is 10
Value of b is 11
Value of name is Krishna

Previous                                                    Next                                                    Home