Sunday, 5 July 2020

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

No comments:

Post a Comment