当前位置:网站首页>Template engine - FreeMarker first experience
Template engine - FreeMarker first experience
2022-06-26 00:57:00 【Everything will always return to plain】
Catalog
1、 summary
FreeMarker It's a template engine : A template based method 、 Generate text for output ( Anything from HTML Formatted text is used to automatically generate source code ) General tools for .
It is for Java A development package or class library provided by a programmer .
It's not for end users , It's an application for programmers that can be embedded in the products they develop .
For detailed introduction, you can read the introduction on the official website by yourself : FreeMarker Java Template Engine

FreeMarker Template files mainly include 5 Component composition :
name | Introduce |
Data model | All data that the template can use |
Text | The direct output part |
notes | namely <#--...--> The format will not output |
interpolation (Interpolation) | namely ${..} perhaps #{..} Part of the format , Part of the data model will be used instead of the output |
FTL Instructions | FreeMarker Instructions , and HTML The mark is similar to , Add... Before your name # To distinguish , No output . |
1.1 Data model
FreeMarker( And template developers ) Don't care how the data is calculated ,FreeMarker Just know what the real data is .
All the data that the template can use is packaged into data-model Data model .

Detailed introduction : Template + data-model = output - Apache FreeMarker Manual
1.2 Common tags for templates
stay FreeMarker The template can include the following specific sections :
label | Introduce |
${…} | be called interpolations,FreeMarker The actual value will be substituted in the output . |
${name} | You can get root in key by name Of value. |
${person.name} | You can get the member variable as person Of name attribute |
<#…> | FTL Mark (FreeMarker Template language tags ): Be similar to HTML Mark , In order to HTML Mark distinction |
<@> | macro , Custom tag |
notes | Included in <#-- and -->( instead of ) Between |
1.3 Template common commands
1、if Instructions : Branch control statement .
<#-- if Instructions -->
<#if sex=1>
Gender is male
<#elseif sex = 0>
Gender is female
<#else>
Gender is unknown
</#if>2、list、break Instructions :list Instruction is a typical iterative output instruction , For iterating sets in the output data model .
<#list weeks as w>
<#if w_has_next> <#-- Whether there is a next object -->
,
</#if>
<#if w = " Thursday ">
<#break> <#-- Jump out of iteration -->
</#if>
${w_index} <#-- The index value of the current variable --> = ${w}
</#list>3、 include Instructions :include The function of instructions is similar to JSP Contains instructions for , Used to contain the specified page .
<#include "template01.ftl">
Write the address of the template directly , because template01.ftl In the same directory as the current template , So you can write the file name directly .
4、 assign Instructions : It is used to create or replace a top-level variable for the template page
<#assign name = " Everything will always return to plain " />
${name}
1.4 Built in functions
FreeMarker Some built-in functions are also provided to transform the output , Any variable can be followed by ?,? Followed by the built-in function , You can convert the output variables through built-in functions . Here are the commonly used built-in string functions :
function | explain |
html | html Character escape |
cap_first | The first letter of the string becomes uppercase |
lower_case | The lowercase form of a string |
upper_case | The upper case form of the string |
trim | Remove the space at the beginning and end of the string |
substring | Truncated string |
lenth | Take the length |
size | The number of elements in the sequence |
int | The integer part of a number ( such as - 1.9?int Namely - 1) |
Example
${name?length}2、 Freemarker Basic use of
2.1 Construct the environment
The first is the construction environment , Let's just build one springBoot project .


The above Apache Freemarker On the hook ,Springboot All help us integrate relevant dependencies .
Then it is to create a folder and src At the same level , It is specially used to put template files .

2.2 Write code
Then go inside and build fremarker file .

Be careful , Suffix is .ftl.
The contents of my documents are those described above .

Then write a test class to test .
@Test
void test01() throws Exception {
//1. establish freeMarker Configure the instance
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
//2. Set up the template loader : Start loading template
cfg.setDirectoryForTemplateLoading(new File("templates"));
//3. Creating a data model
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("username", " Zhang San ");
dataModel.put("sex", 0);
List<String> weeks = new ArrayList<>();
weeks.add(" Monday ");
weeks.add(" Tuesday ");
weeks.add(" Wednesday ");
weeks.add(" Thursday ");
weeks.add(" Friday ");
dataModel.put("weeks",weeks);
//4. Access to the template
Template template = cfg.getTemplate("template.ftl");
template.process(dataModel, new PrintWriter(System.out));// Output content in the console
template.process(dataModel, new PrintWriter(new File("C:\\Users\\Administrator\\Desktop\\b.txt")));// Output the contents in the file
}2.3 test result


2.4 String template
In one case, we didn't write ftl When you file , You can use it by yourself java Code custom template .
@SpringBootTest
class FreeMarkerApplicationTests {
private Configuration conf;
@BeforeEach
public void init() {
conf = new Configuration(Configuration.VERSION_2_3_29);
}
@Test
void test02() throws Exception {
// 2、 Specify loader StringTemplateLoader() String loader
conf.setTemplateLoader(new StringTemplateLoader());
// 3、 Create a string template
String templateString = " Welcome ,${username}"; // String template
Template template = new Template("",new StringReader(templateString),conf); // Create a template from a string
//4、 Structural data
Map<String,Object> dateModel = new HashMap<>();
dateModel.put("username"," Li Si ");
//5、 Processing templates
template.process(dateModel, new PrintWriter(new File("C:\\Users\\Administrator\\Desktop\\b.txt")));// Output in file
}
}Look at the effect .

边栏推荐
- “Method Not Allowed“,405问题分析及解决
- Send mail tool class
- Idea view unit test coverage
- 【系统架构】-什么是MDA架构、ADL、DSSA
- Msp430f5529lp official board (red) can not debug the problem
- Spark log analysis
- mysql cluster
- Electronic training.
- 1-11solutions to common problems of VMware virtual machine
- Graduation season | fitting the best self in continuous exploration
猜你喜欢

C IO stream (II) extension class_ Packer

【图像检测】基于高斯过程和Radon变换实现血管跟踪和直径估计附matlab代码
![Making 3D romantic cool photo album [source code attached]](/img/81/68a0d2f522cc3d98bb70bf2c06893a.png)
Making 3D romantic cool photo album [source code attached]

Optimized three-dimensional space positioning method and its fast implementation in C language

ciscn_ 2019_ en_ two

.net使用Access 2010数据库

STL tutorial 5-basic concepts of STL and the use of string and vector

Establish a j-link GDB cross debugging environment for Px4

How to deliver a shelter hospital within 48 hours?

Modelsim simulation FFT core cannot be simulated solution (qsys)
随机推荐
C IO stream (II) extension class_ Packer
模板引擎——FreeMarker初体验
“Method Not Allowed“,405问题分析及解决
Typescript for Web Learning
How to deliver a shelter hospital within 48 hours?
Methods to realize asynchrony
[TSP problem] solving traveling salesman problem based on Hopfield neural network with matlab code
debezium
Optimized three-dimensional space positioning method and its fast implementation in C language
Example: use C # Net to teach you how to develop wechat official account (21) -- using wechat to pay online collection: H5 method
Error 65:access violation at 0x58024400: no 'read' permission
Msp430f5529lp official board (red) can not debug the problem
Android cache usage tool class
安卓缓存使用工具类
Mining pit record of modified field information in Dameng database
1-9network configuration in VMWare
Making 3D romantic cool photo album [source code attached]
flink报错:No ExecutorFactory found to execute the application
The development context of Ba Kong Yuan universe industry
关于EF翻页查询数据库