当前位置:网站首页>模板引擎——FreeMarker初体验
模板引擎——FreeMarker初体验
2022-06-25 22:49:00 【一切总会归于平淡】
目录
1、概述
FreeMarker 是一款模板引擎:一种基于模板的、用来生成输出文本(任何来自于 HTML格式的文本用来自动生成源代码)的通用工具。
它是为 Java 程序员提供的一个开发包或者说是类库。
它不是面向最终用户,而是为程序员提供的可以嵌入他们开发产品的一款应用程序。
详细介绍大家可以自行看官网的介绍 : FreeMarker Java Template Engine
FreeMarker模板文件主要有5个部分组成:
名称 | 介绍 |
数据模型 | 模板能用的所有数据 |
文本 | 直接输出的部分 |
注释 | 即<#--...-->格式不会输出 |
插值(Interpolation) | 即${..}或者#{..}格式的部分,将使用数据模型中的部分替代输出 |
FTL指令 | FreeMarker指令,和HTML标记类似,名字前加#予以区分,不会输出。 |
1.1 数据模型
FreeMarker(还有模板开发者)并不关心数据是如何计算的,FreeMarker 只是知道真实的数据是什么。
模板能用的所有数据被包装成 data-model 数据模型。
详细介绍 : Template + data-model = output - Apache FreeMarker Manual
1.2 模板的常用标签
在FreeMarker模板中可以包括下面几个特定部分:
标签 | 介绍 |
${…} | 称为interpolations,FreeMarker会在输出时用实际值进行替代。 |
${name} | 可以取得root中key为name的value。 |
${person.name} | 可以取得成员变量为person的name属性 |
<#…> | FTL标记(FreeMarker模板语言标记):类似于HTML标记,为了与HTML标记区分 |
<@> | 宏,自定义标签 |
注释 | 包含在<#--和-->(而不是)之间 |
1.3 模板常用命令
1、if指令 :分支控制语句。
<#-- if 指令 -->
<#if sex=1>
性别是男
<#elseif sex = 0>
性别是女
<#else>
性别是未知
</#if>
2、list、break指令 :list指令时一个典型的迭代输出指令,用于迭代输出数据模型中的集合。
<#list weeks as w>
<#if w_has_next> <#--是否存在下一个对象-->
,
</#if>
<#if w = "星期四">
<#break> <#--跳出迭代-->
</#if>
${w_index} <#--当前变量的索引值--> = ${w}
</#list>
3、 include 指令 :include指令的作用类似于JSP的包含指令,用于包含指定页。
<#include "template01.ftl">
直接写模板的地址,因为template01.ftl和当前模板在同一目录下,所以可以直接写文件名。
4、 assign指令 :它用于为该模板页面创建或替换一个顶层变量
<#assign name = "一切总会归于平淡" />
${name}
1.4 内置函数
FreeMarker还提供了一些内建函数来转换输出,可以在任何变量后紧跟?,?后紧跟内建函数,就可通过内建函数来转换输出变量。下面是常用的内建的字符串函数:
函数 | 说明 |
html | html字符转义 |
cap_first | 字符串的第一个字母变为大写形式 |
lower_case | 字符串的小写形式 |
upper_case | 字符串的大写形式 |
trim | 去掉字符串首尾的空格 |
substring | 截字符串 |
lenth | 取长度 |
size | 序列中元素的个数 |
int | 数字的整数部分(比如- 1.9?int 就是- 1) |
示例
${name?length}
2、 Freemarker的基本使用
2.1 构造环境
首先是构造环境,我们直接建一个springBoot项目。
将上面的 Apache Freemarker 勾上 ,Springboot 都帮我们整合好相关依赖了。
然后就是建一个文件夹 和 src 同级,专门用来放模板文件。
2.2 编写代码
再往里建立fremarker 文件。
注意,后缀是.ftl。
我的文件内容就是上面介绍的那些。
然后写一个测试类来测试。
@Test
void test01() throws Exception {
//1.创建freeMarker配置实例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
//2.设置模板加载器:开始加载模板
cfg.setDirectoryForTemplateLoading(new File("templates"));
//3.创建数据模型
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("username", "张三");
dataModel.put("sex", 0);
List<String> weeks = new ArrayList<>();
weeks.add("星期一");
weeks.add("星期二");
weeks.add("星期三");
weeks.add("星期四");
weeks.add("星期五");
dataModel.put("weeks",weeks);
//4.获取模板
Template template = cfg.getTemplate("template.ftl");
template.process(dataModel, new PrintWriter(System.out));//在控制台输出内容
template.process(dataModel, new PrintWriter(new File("C:\\Users\\Administrator\\Desktop\\b.txt")));//在文件输出内容
}
2.3 测试结果
2.4 字符串模板
有一种情况就是我们没有写ftl 文件的时候,这时候就可以自己使用java代码自定义模板。
@SpringBootTest
class FreeMarkerApplicationTests {
private Configuration conf;
@BeforeEach
public void init() {
conf = new Configuration(Configuration.VERSION_2_3_29);
}
@Test
void test02() throws Exception {
// 2、指定加载器 StringTemplateLoader() 字符串加载器
conf.setTemplateLoader(new StringTemplateLoader());
// 3、创建字符串模板
String templateString = "欢迎你,${username}"; // 字符串模板
Template template = new Template("",new StringReader(templateString),conf); // 通过字符串创建模板
//4、构造数据
Map<String,Object> dateModel = new HashMap<>();
dateModel.put("username","李四");
//5、处理模板
template.process(dateModel, new PrintWriter(new File("C:\\Users\\Administrator\\Desktop\\b.txt")));//在文件内输出
}
}
看看效果。
边栏推荐
- 认识map
- Compiler Telegram Desktop end (tdesktop) en utilisant vs2022
- 每日一问:线程和进程的区别
- Leetcode 513. Find the value in the lower left corner of the tree
- mysql
- . user. PHP website installation problems caused by INI files
- 案例:绘制Matplotlib动态图
- Implementation notes of least square fitting conic in stm32
- 【系统架构】-什么是MDA架构、ADL、DSSA
- Anti shake and throttling
猜你喜欢
Blob
Apache foundation officially announced Apache inlong as a top-level project
关于HC-12无线射频模块使用
Flink报错:Error: A JNI error has occurred, please check your installation and try again
Final review [machine learning]
Qt优秀开源项目之九:qTox
Leetcode 513. Find the value in the lower left corner of the tree
随便画画的
Unified gateway
Optimized three-dimensional space positioning method and its fast implementation in C language
随机推荐
Methods of modifying elements in JS array
Preorder and middle order traversal of forest
Music spectrum display toy -- implementation and application of FFT in stm32
Example: use C # Net to teach you how to develop wechat official account (21) -- using wechat to pay online collection: H5 method
Methods to realize asynchrony
[system architecture] - what are MDA architecture, ADL and DSSA
flink报错:No ExecutorFactory found to execute the application
"Seamless" deployment of paddlenlp model based on openvinotm development kit
Kylin
制作3D浪漫炫酷相册【附源码】
[机缘参悟-30]:鬼谷子-内揵篇-同理心,站在对方的立场,拉近与对方的心理距离
Typescript for Web Learning
渗透工具-Burpsuite
mtb13_ Perform extract_ blend_ Super{candidate (primaryalternate) \u unique (nullable filtering \foreign\index\granulati
论文中英文大小写、数字与标点的正确撰写方式
sqlserver 区分字符串中字母大小写
SQL to retain the maximum value sorted by a field
What training brings happiness
Explanation of chip processing manufacturer__ What is ICT? What is the main test? Advantages and disadvantages of ICT testing?
Motor monitoring system based on MCGS and stm32