FreeMarker notes Chapter 4 others, freemarker Chapter 4

Source: Internet
Author: User
Tags implement definition

FreeMarker notes Chapter 4 others, freemarker Chapter 4
4.1 Introduction to custom commands 4.1.1

Custom commands can be defined using macro commands. If the Java programmer does not want to implement definition commands in the template, but implements the definition of commands in the Java language, the freemarker. template. TemplateDirectiveModel class can be used for extension. 4.1.2 Basic Content

A macro is a template snippet with a variable name. You can use macros as custom commands in the template to perform repetitive work. For example, create a macro variable to print the large "hello Joe! ";

<#macro greet>    <font size="+2">Hello Joe!</font></#macro>

You can use the custom command in the FTL tag by @ instead.

4.1.3 Parameters

We only define a variable in the greet macro, person;

<#macro greet person>    <font size="+2">Hello ${person}!</font></#macro>

The macro can be used as follows:

<@greet person="Fred"/>and<@greet person="Batman"/>

Double quotation marks can be removed,<@greet person=Fred/>

You can set the default value for multiple parameters. Otherwise, you must specify multiple parameters:

<#macro greet person color="black">    <font size="+2" color="${color}">Hello ${person}!</font></#macro>

Then you can use it like this.

<@greet person="Fred"/>

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/macro. ftl

<H2> No parameter 


4.1.4 nested content

Custom commands can be nested, similar to predefined commands:<#if ...>nested content</#if>. For example, the following example creates a border for nested content;

<#macro border>    <table border=4 cellspacing=0 cellpadding=4>        <tr>            <td>                <#nested>            </td>        </tr>    </table></#macro>

<# Nested> the tag executes the template code block between the start and end labels. For example:

<@border>The bordered text</@border>


<table border=4 cellspacing=0 cellpadding=4>    <tr>        <td>            The bordered text        </td>    </tr></table>

<# Nested> the command can be executed multiple times;

<#macro do_thrice>    <#nested>    <#nested>    <#nested></#macro>

Use Time:




If you do not use the nested command, the nested content will be executed. If you accidentally write it as follows:

<@greet person="Joe">    Anything.</@greet>

The output is:

<font size="+2">Hello Joe!</font>

Nested content is ignored because greet does not use the nested command;

The nested content can be other FTL commands, and other custom commands can also be included.

<@border>    <ul>        <@do_thrice>            <li><@greet person="Joe"></li>        </@do_thrice>    </ul></@border>

In the nested content, macro local variables are invisible;

<#macro repeat count>    <#local y="test">    <#list 1..count as x>        ${y} ${count}/${x} : <#nested>    </#list></#macro><@repeat count=3>${y!"?"} ${x!"?"} ${count!"?"}</@repeat>

The output is as follows:

test 3/1: ? ? ?test 3/2: ? ? ?test 3/3: ? ? ?

The setting of different local variables is called by each macro, so it will not lead to confusion;

<#macro test foo>${foo} (<#nested>) ${foo}</#macro><@test foo="A"><@test foo="B"><@test foo="C"/></@test></@test>


A (B (C () C) B) A
4.1.5 macros and cyclic Variables

The name of the cyclic variable is given, and the variable value is set by the instruction itself.

<# Macro do_thrice> <# nested 1> <# nested 2> <# nested 3> </# macro> <p> <# -- use custom loop variables; replace as --> <@ do_thrice; x> do_something :$ {x} </@ do_thrice> </p>


do_something : 1 do_something : 2 do_something : 3 

Example:/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/nested. ftl

<H3> macro and cyclic variables 

A macro can use multiple cyclic variables (the order of variables is important ):

<#macro repeat count>    <#list 1..count as x>        <#nested x, x/2, x==count>    </#list></#macro>

When using:

<@repeat count=4 ; c, halfc, last>    ${c}.${halfc}<#if last> Last!</#if></@repeat>

The output is as follows:

\1. 0.5\2. 1\3. 1.5\4. 2 Last!

Example:/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/nested. ftl

<H3> one macro can use multiple cyclic variables 

If the variable specified after the semicolon is less or more, the extra variable will be ignored;

    @repeat count=4 ; c, half>        ${c}. ${half}    </@repeat>
4.1.6 Advanced custom commands and macros

You can also define methods in FTL. For more information, see function commands;

Maybe you are interested in the namespace. Namespaces help you organize and reuse macros that you often use; 4.2 define variables in templates

You can access a variable defined in the template, just like the variable on the root of the data model. This variable has a higher priority than a parameter with the same name defined in the data model. If you happen to define a variable named "foo", and there is a variable named "foo" in the data model, then, the variables in the template will hide (rather than overwrite!) the variables on the root of the data model !).

Three types of variables can be defined in the template:

  • Simple Variables: It can be accessed from any location in the template, or fromincludeTemplate access introduced by the command. AvailableassignOrmacroCommand to create or replace these variables.
  • Local variable: They can only be set in the macro definition body and only visible in the macro. The life cycle of a local variable is only a macro call process. AvailablelocalTo create or replace local variables.
  • Loop Variable: Cyclic variables are executed by commands (suchlist) Automatically created, and they are only valid in the start and end labels of the command. Macro parameters are local variables rather than circular variables.

UseassignCreate and replace variables;

/FreeMarker-hello-web/src/main/webapps/WEB-INF/ftl/4/variable. ftl

<H3> simple variable 


Simple variable 14

Local variables also hide simple variables with the same name (rather. Loop variables also hide (not overwrite) local variables with the same name and simple variables.

Instance:/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/variable. ftl

<# Macro test> 2. $ {x} <br> <# local x = "local"> 3. $ {x} <br> <# list ["loop"] as x> 4. $ {x} <br> </# list> 5. $ {x} <br> </# macro> <p> <# assign x = "plain"> 1. $ {x} <br> <@ test/> 6. $ {x} <br> <# list ["loop"] as x> 7. $ {x} <br> <# assign x = "plain2"> <# -- replace the simple variable x here --> 8. $ {x} <br> </# list> 9. $ {x} </p>


1. plain2. plain3. local4. loop5. local6. plain7. loop8. loop9. plain2

Internal loops can hide variables of external loops;

Instance:/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/variable. ftl

        <#list ["loop 1"] as x>            ${x}<br>            <#list ["loop 2"] as x>                ${x}<br>                <#list ["loop 3"] as x>                    ${x}<br>                </#list>                ${x}<br>            </#list>            ${x}<br>        </#list>


loop 1loop 2loop 3loop 2loop 1

Sometimes a variable hides a variable of the same name in the data model. to access a variable in the data model, you can use a special variable.globals.

Instance:/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/variable. ftl

        <#assign user="Cindy">        ${user}, ${.globals.user}   

/FreeMarker-hello-web/src/main/java/org/yejq/fre/service/Exercises. java

    public void testVariable(Model model){        model.addAttribute("user", "lucy");    }

Test: http: // localhost/test/4/variable/testVariable. The output result is as follows:

Cindy, lucy
4.3 introduction to namespace 4.3.1

If you want to create a set of macros, functions, and other variables that can be reused, it is usually referenced in termsLibrary, Using a namespace is inevitable; 4.3.2 creating a library


<#macro copyright date>    <p>Copyright (C) ${date} Julia Smith. All rights reserved.</p></#macro><#assign mail="">

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/namespace. ftl

<H3> import using import 


Use import to import Copyright (C) 2014-2016 Julia Smith. All rights

Test different namespaces;


<#macro copyright date>    <p>Copyright (C) ${date} Julia Smith. All rights reserved.    <br>Mail: ${mail}       </p></#macro><#assign mail="">

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/namespace. ftl

<H3> demonstrate different namespaces 

Test: http: // localhost/test/4/namespace/null4.3.3 write variables in the introduced namespace

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/namespace. ftl

        <#import "../lib/my_test.ftl" as my>        ${my.mail}<br>        <#assign mail="" in my>        ${my.mail}

Http: // localhost/test/4/namespace/null, output: 
4.3.4 namespace and Data Model

Variables in the data model are visible at any position. If there is a variable named user in the data modellib/my_test.ftlYou can also access TA.


<#macro copyright date>    <p>Copyright (C) ${date} ${user} Julia Smith. All rights reserved.    <br>Mail: ${mail}       </p></#macro><#assign mail="${user}">

/FreeMarker-hello-web/src/main/java/org/yejq/fre/service/Exercises. java

    public void testNamespace(Model model){        model.addAttribute("user", "lucy");    }

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/namespace. ftl

<H3> variables in the data model are visible anywhere 

Test: http: // localhost/test/4/namespace/testNamespace? 11. output result:

Copyright (C) 2014-2015 lucy Julia Smith. All rights reserved. Mail: 
4.3.5 lifecycle of a namespace

Namespace usedimportThe path written in the command to identify. If you wantimportThis path will only be the first timeimportReference to create a namespace execution template. TheimportCreate a hash table as the "door" to access the same namespace ".

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/namespace. ftl

<H3> namespace claim period 

Access: http: // localhost/test/4/namespace/null, output:

Namespace declaration cycle,, jsmith@acme.comjsmith @,, jsmith@other.comjsmith @,,

Note that namespaces are not hierarchical and they exist independently of each other. Then, ifimportThe name is null N2, and N2 is not in N1. N1 only accesses N2 through a hash table. This is the sameimportN2, and then directly access the namespace N2 is the same process.

Each template execution process has a set of private namespaces. Every execution of a template is a separate and orderly process. They only exist for a short period of time, and the page is used to render the content, and then disappear with all the filled namespaces. 4.3.6 compile a library for others


Standard library path format:


If your company's homepage is, then;


An important rule is that the path should not contain uppercase letters, and winForm should be changed to win_form; 4.4 blank processing 4.4.1

Let's take a look at this template;

After output according to Freemarker rules:

Such a large amount of white space is a headache, and it is unnecessary to increase the size of the HTML file after processing;

FreeMarker provides the following tools to handle this problem:

  • A tool that ignores the blank space of some files (the blank space is removed in the parsing phase)
    • Strip white space: This feature automatically ignores the white space around the FTL tag. This feature can be used and disabled at any time through templates;
    • Fine-tuning command:t,rtAndltBy using these commands, FreeMarker can be clearly told to ignore some blank spaces;
    • FTL Parametersstrip_text: This will delete all top-level text from the template. It is useful for a template. It contains some defined macros because it can remove macro definitions and line breaks from other top-level commands, which improves the readability of the template;
  • Remove blank tools from output (remove near blank)
    • compressCommand

It automatically ignores two typical blank spaces:

  • Indent blank and trailing blank at the end of the line; if this line contains<#if ...>x, Then the blank space will not be ignored, because x is not a tag. One row has<#if ...> <#list ...>In this way, the blank space is not ignored, because the spaces between labels are embedded in the blank space;
  • The gaps added between these commands will be ignored: macro, function, assign, global, local, ftl, import;

After the blank space is stripped, the output in the preceding example is:

The strip white space function can be enabled or disabled in the ftl instruction template. Enabled by default. Enabling split blank does not reduce the execution efficiency of the template. The split blank operation is completed when the template is loaded.

The split blank can be closed for a single line, that is, using the nt command; 4.4.3 using the compress command

In contrast to the blank strip, this work is directly based on the output content of the production, rather than the template. It removes indentation, empty rows, and repeated spaces/tabs;

For the following code:

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/compress. ftl

<H2> use the compress command to remove indentation from the output content, empty rows and spaces/tabs 


<H2> use the compress command to remove indentation, blank lines, and spaces/tabs from the output content 

Due to backward compatibility, user-defined commands named compress exist and have a single_line attribute. If this attribute is set to true, the line break is removed;

<H3> @ compress attributes single_line 

It does not seem to work, but # compress is single_line; 4.5 Replace (square brackets) syntax

Available only after version 2.3.4;

Use in commands and comments[]Replace<>;

[#list ...]...[/list][@mymacro .../][#-- the comment --]

To use this syntax to replace the default syntax, you need to use [# ftl] to start the template.

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/4/ftl. ftl

[# Ftl] <! Doctype html> 

Test: http: // localhost/test/4/ftl/null

FreeMarker cross-Display

<# List data. dayAddCount as c> This is unnecessary. The list has an index attribute. For example, if your list contains as c, this attribute is c_index. Here, you can use $ {data. dayAddCount [d_index]} Get the c you want
There is another way, but it is not necessary, and the performance consumption is larger than the above.
In <# list data. dayAddCount as c>, <# if d_index = c_index >$ {c !} </# If>

How to judge in a loop in freemarker is as shown in <# list aaalist as formfield> </# list> In formfield judgment

If the formfield contains strings, you can directly use the upstairs ones. If the formfield contains class objects, you must use
<# If class. Attribute = ""> </# if>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.