FreeMarker is a free, open source Java-based template engine. It is a text-based template output tool with rich expressions and the ability to customize expressions. Freemarker can present data prepared at the back end, through Freemarker expressions, on the front end page. Web pages, often used to generate HTML in software projects, can export excel in complex styles by generating output files based on templates.

FreeMarker working diagram

Springboot is configured in the project

Add maven dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Copy the code

Configuration:

spring: freemarker: cache: false suffix: .ftl template-loader-path: classpath:/templates content-type: text/html; Charset = UTF-8 Settings: number_format: 0Copy the code

Commonly used method

Before I get to Freemarker’s method, I’d like to make fun of the fact that one of the grossest things about Freemarker is a null error. If your page expression is null, it will generate an error, so you need to check if it is null before using it, and sometimes the page will generate an error because of this.

Get the element value:

<#if (msg)! =""> ${msg} </#if>Copy the code

Get the values in the map:

${map["name"]}
Copy the code

Foreach, loop through list, short judgment:

<#if students ?? && students ? size gt 0> <#list students as student> ${student.name} ${student.age} ${student.sex} </#list> </#if>Copy the code

If… Methods the else:

<#if type= =1 > type=1 <#if type= =2 > type=2 </#if> string('yes', 'no')) = = 'yes' > < span > to < / span > < # else > < span > right < / span > < / # if > # value if more judgment < # the if flag = = "1" > < span > 1 < / span > < # elseif Flag = = "2" > < span > 2 < / span > < # elseif flag = = "3" > < span > 3 < / span > < # else > < span > apart from the 1, 2, 3, < / span > < / # if >Copy the code

Get session values:

GetSession ().setAttribute("userId",userId); <#if Session["userId"] <#if Session["userId"] exists> ${Session["userId"]} </#if>Copy the code

Freemarker formatting time:

2020-05-09 13:59:32 ${createTime? string('yyyy-MM-dd hh:mm:ss')}Copy the code

Use the include tag to introduce additional pages:

<div style="height: 80px; position: fixed; width: 350px; text-align: center; background-color: white;" > <div class="col-md-6"> <a href="#" style="text-decoration: none; color: #000000; line-height: 80px; font-size: 22px;" >< span class="glyphicon glyphicon-edit"></span> Write a text </a> <div >< div class=" col-mD-6 ">< a href="#" style="text-decoration: none; color: #000000; line-height: 80px; font-size: 22px;" >< span class="glyphicon glyphicon-trash"></span> draft box </a> </div> </div> Use the include tag <#include "right.ftl">Copy the code