Getting started with FreeMarker

Posted by b-real on Thu, 13 Feb 2020 07:42:30 +0100

1. What is FreeMarker

FreeMarker is a template engine: a template based, used to generate output text (any text from HTML format is used to automatically generate the source
Code). It is a development package or class library for Java programmers.

FreeMarker's design is actually used to generate HTML pages, especially through the implementation of MVC (model view controller-
View controller) mode.

2 application scenario of FreeMarker

(1) Dynamic page
Generate page file based on template configuration and expression, which can be accessed by client like jsp
(2) Page static
FreeMarker can be used to make web pages static for applications that frequently use database for query but have little content update in the system, so as to avoid
A large number of database access requests are made to improve the performance of the website
(3) Code generator
Automatically generate page or code according to background configuration

Features and highlights of freemarker

  • Powerful template language: conditional block, iteration, assignment, string and arithmetic operation and formatting, macro and function, coding and other functions;
  • Multi purpose and light weight: Zero dependency, output in any format, template can be loaded from anywhere (pluggable), configuration options are rich;
  • Intelligent internationalization and localization: sensitive to locale and date / time formats.
  • XML processing function: put dom-s into XML data model and traverse them, and even process their declaration
  • General data model: java objects are exposed to templates as variable trees through pluggable adapters.

3 basic use of FreeMarker

3.1 tectonic environment

Introduce the corresponding jar

        <!--freemarker Core package -->

3.2 introduction cases

(1) Create template.ftl


Welcome: ${username}

(2) Using freemarker to complete the operation

package com.shunli.autocodeutils.testfreemark;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

 * @author shunli
 * @Description:
 * @create 2020/2/13
 * @since 1.0.0
public class FreemarkTest01 {
    public void testProcessTemplate() throws Exception {

        //1. Create a freeMarker configuration instance
        Configuration cfg = new Configuration();
        //2. Set template loader: start loading template and load template in cache
        cfg.setTemplateLoader(new FileTemplateLoader(new File("templates")));
        //3. Create data model
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("username", "Zhang San");
        //4. Get template
        Template template = cfg.getTemplate("temp01.ftl");
         * 5.Process template content (i. output to file)
         * process:
         * Parameter 1: Data Model (map set)
         * Parameter 2: Writer object (file, console)
        * */
        //i. Export to file
        //template.process(dataModel, new FileWriter(new File("C:\Users\ThinkPad\Desktop\ihrm\day12 \ \ test \ \ aa.text"));
        //i. Print to console
        template.process(dataModel, new PrintWriter(System.out));//Output content in the console

console output

3.3 string template

package com.shunli.autocodeutils.testfreemark;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.Before;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

 * @author shunli
 * @Description:
 * @create 2020/2/13
 * @since 1.0.0
public class FreemarkTest02 {

    private Configuration conf;
    public void init() {
        conf = new Configuration();

    public void testProcessTemplateString() throws Exception {
        String templateString = "Welcome: ${username}";
        Map<String,Object> dataMap = new HashMap();
        dataMap.put("username","Zhang San");
        StringWriter out = new StringWriter();
         * Custom template
         * 1.Template name
         * 2.Body content of template
         * 3.configuration object
        Template template = new Template("templateString...",new StringReader(templateString),conf);
        //Process template content
        template.process(dataMap, out);


4 Freemarker template

4.1 overview

FreeMarker template file mainly consists of five parts:

  1. Data model: all data that the template can use
  2. Text, direct output part
  3. Note, i.e -->Format will not be output
  4. Interpolation: that is ${ } or... }Part of the format, which replaces the output with part of the data model
  5. FTL instruction: FreeMarker instruction, similar to HTML tag, can't be output because it's distinguished by adding "ා" before the name.

4.2 data model

FreeMarker (and template developers) don't care about how the data is calculated. FreeMarker just knows what the real data is. Template can be used
All data of is packaged as data model data model

4.3 common labels of formwork

The FreeMarker template can include the following specific parts:

  1. N. }: called interactions, FreeMarker replaces the actual value when it outputs.
    ${name} can get the value with the key as name in root.
    ${} can get the name attribute with member variable as person
  2. "..." >: FTL markup (FreeMarker template language markup): similar to HTML markup, in order to distinguish it from HTML markup
  3. < @ > macro, custom label
  4. Note: included between < × - and -- > (instead of)

4.4 common instructions of template

if directive

  <#if condition>
  <#elseif condition2>
  <#elseif condition3>      

list and break instructions
list instruction is a typical iterative output instruction, which is used to iterate the set in the output data model

<#list sequence as item>
   In addition, there are two special loop variables when iterating over a collection object:
       a. item_index: the index value of the current variable.
       b. Item has next: whether the next object exists
       You can also use the < break > instruction to jump out of an iteration
        < list ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] as x >
           ${x_index +1}.${x} <#if x_has_next>,</#if>
            < if x = "Thursday" >

include instruction
The include instruction is similar to the JSP include instruction, which is used to contain the specified page. The syntax format of the include instruction is as follows

<#include filename [options]></#include>
           In the above syntax format, the two parameters are interpreted as follows
           a. filename: this parameter specifies the template file to be included
           b. Options: this parameter can be omitted. It specifies the options when it is included, including encoding and parse
  Specifies the decode set to use when containing the page, while parse specifies that the
           Contains whether to resolve as an FTL file. If the parse option value is omitted, it defaults to true

assign directive
It is used to create or replace a top-level variable for the template page

<#assign name = zhangsan />

Built-in function
FreeMarker also provides some built-in functions to convert the output. You can use built-in functions after any variable and after any variable
Number to convert the output variable. The following are common built-in string functions:

 ? html:html character escape
 ? cap? First: the first letter of the string becomes uppercase
 ? lower case: lowercase form of string
 ? upper case: upper case of string
 ? trim: remove the space at the beginning and end of the string
 ? substring: truncation string
 ? lenth: take the length
 ? size: number of elements in the sequence
 ? int: integer part of a number (for example - 1.9?int is - 1)
 ? replace: string replacement
37 original articles published, praised 8, visited 20000+
Private letter follow

Topics: FreeMarker Java Junit JSP