FreeMarker是一款免费的Java模板引擎,是一种基于模板和数据生成文本(HMLT、电子邮件、配置文件、源代码等)的工具,它不是面向最终用户的,而是一款程序员使用的组件。html
FreeMarker最初设计是用来在MVC模式的Web开发中生成HTML页面的,因此没有绑定Servlet或任意Web相关的东西上,因此它能够运行在非Web应用环境中。java
FreeMarker初版在1999年未就发布了,2002年初使用JavaCC(Java Compiler Compiler是一个用Java开发的语法分析生成器)重写了FreeMarker的核心代码,2015年FreeMarker代码迁移到了Apache下。git
GitHub地址:https://github.com/apache/freemarker程序员
FreeMarker模板存储在服务器上,当有用户访问的时候,FreeMarker会查询出相应的数据,替换模板中的标签,生成最终的HTML返回给用户,以下图:github
基础使用分为3部分,这3部分组成了FreeMarker:golang
指令是FreeMarker用来识别转换的特殊标签,表达式是标签里具体的语法实现,其余部分是一些很差分类的模板。web
使用FTL(freemarker template language)标签来调用指令。spring
指令速览:apache
下来咱们分别来看每一个指令对应具体使用。数组
assign 分为变量和代码片断声明两种。
能够是单变量声明,或多变量声明,下面是多变量声明的示例:
<#assign name="adam" age=18 "sex"="man"> ${name} - ${age} - ${"sex"}
单个变量的话,只写一个就能够了。
<#assign code> <#list ["java","golang"] as c> ${c} </#list> </#assign> ${code}
其中 ${code}
是用来执行方法的,若是不调用话,代码片断不会执行。
attempt(尝试), recover(恢复)指令相似于程序的try catch,示例以下:
<#attempt> i am ${name} <#recover> error name </#attempt>
若是有变量“name”就会正常显示,显示“i am xxx”,若是没有变量就会显示“error name”。
<#compress> 1 2 3 4 5 test only I said, test only </#compress> 1 2 3 4 5 test only I said, test only
效果以下:
对空白不敏感的格式,移除空白行仍是挺有用的功能。
<#escape x as x?html> ${firstName} ${lastName} </#escape>
上面的代码,相似于:
${firstName?html} ${lastName?html}
Java代码:
@RequestMapping("/") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("firstName", "<span style='color:red'>firstName</span>"); modelAndView.addObject("lastName", "lastName"); return modelAndView; }
最终的效果是:
单问号后面跟的是操做函数,相似于Java中的方法名,html属于内建函数的一个,表示字符串会按照HTML标记输出,字符替换规则以下:
<
替换为 <
>
替换为 >
&
替换为 &
"
替换为 "
HTML代码:
<#escape x as x?html> <#noescape> ${firstName} </#noescape> ${lastName} </#escape>
Java代码:
@RequestMapping("/") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("firstName", "<span style='color:red'>firstName</span>"); modelAndView.addObject("lastName", "lastName"); return modelAndView; }
最终效果:
代码格式:
<#function name param1 param2 ... paramN> ... <#return returnValue> ... </#function>
示例代码以下:
<#function sum x y z> <#return x+y+z> </#function> ${sum(5,5,5)}
注意:function若是没有return是没有意义的,至关于返回null,而function之中信息是不会打印到页面的,示例以下:
<#function wantToPrint> 这里的信息是显示不了的 </#function> <#if wantToPrint()??> Message:${wantToPrint()} </#if>
“??”用于判断值是不是null,若是为null是不执行的。若是不判null直接使用${}打印,会报模板错误,效果以下:
语法以下:
<#global name=value> 或 <#global name1=value1 name2=value2 ... nameN=valueN> 或 <#global name> capture this </#global>
global使用和assign用法相似,只不过global声明是全局的,全部的命名空间都是可见的。
语法以下:
<#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if>
示例以下:
<#assign x=1 > <#if x==1> x is 1 <#elseif x==2> x is 2 <#else> x is not 1 </#if>
语法: <#import path as hash>
示例以下
footer.ftl 代码以下:
<html> <head> <title>王磊的博客</title> </head> <body> this is footer.ftl <#assign copy="来自 王磊的博客"> </body> </html>
index.ftl 代码以下:
<html> <head> <title>王磊的博客</title> </head> <body> <#import "footer.ftl" as footer> ${footer.copy} </body> </html>
最终输出内容:
来自 王磊的博客
语法: <#include path>
示例以下
footer.ftl 代码以下:
<html> <head> <title>王磊的博客</title> </head> <body> this is footer.ftl <#assign copy="来自 王磊的博客"> </body> </html>
index.ftl 代码以下:
<html> <head> <title>王磊的博客</title> </head> <body> <#include "footer.ftl"> </body> </html>
最终内容以下:
this is footer.ftl
输出1-3的数字,若是等于2跳出循环,代码以下:
<#list 1..3 as n> ${n} <#if n==2> <#break> </#if> </#list>
注意:“1..3”等于[1,2,3]。
结果: 1 2
示例以下:
<#list 1..3> <ul> <#items as n> <li>${n}</li> </#items> </ul> </#list>
跳过最后一项
<#list 1..3 as n> ${n} <#sep>,</#sep> </#list>
最终结果:1 , 2 , 3
代码以下:
<#list 1..3 as n> ${n} <#if !n_has_next> 最后一项 </#if> </#list>
使用“变量_has_next”判断是否还有下一个选项,来找到最后一项,最终的结果:1 2 3 最后一项
宏:是一个变量名的代码片断,例如:
<#macro sayhi name> Hello, ${name} </#macro> <@sayhi "Adam" />
至关于声明了一个名称为“sayhi”有一个参数“name”的宏,使用自定义标签“@”调用宏。
输出的结果: Hello, Adam
示例代码以下:
<#assign animal="dog" > <#switch animal> <#case "pig"> This is pig <#break> <#case "dog"> This is dog <#break> <#default> This is Aaimal </#switch>
指令自动忽略空格特性
FreeMarker会忽略FTL标签中的空白标记,因此能够直接写:
<#list ["老王","老李","老张"] as p> ${p} </#list>
即便是这个格式也是没有任何问题的,FreeMarker会正常解析。
字符拼接代码:
<#assign name="ABCDEFG"> ${"Hello, ${name}"}
结果:Hello, ABCDEFG
算术符有五种:
+
-
*
/
%
求余(求模)示例代码:
${100 - 10 * 20}
输出:
-100
${1.999?int}
输出:
1
注意:数值转换不会进行四舍五入,会舍弃小数点以后的。
内建函数:至关于咱们Java类里面的内置方法,很是经常使用,经常使用的内建函数有:时间内建函数、字符内建函数、数字内建函数等。
单问号:在FreeMarker中用单个问号,来调用内建函数,好比: ${"admin"?length}
查看字符串“admin”的字符长度,其中length就是字符串的内建函数。
双引号:表示用于判断值是否为null,好比:
<#if admin??> Admin is not null </#if>
使用contains判断,代码示例:
<#if "admin"?contains("min")> min <#else > not min </#if>
输出:
min
示例代码:
<#assign name="Adam"> ${name?uncap_first} ${name?upper_case} ${name?cap_first} ${name?lower_case}
输出:
adam ADAM Adam adam
更多的字符串内建函数:https://freemarker.apache.org/docs/ref_builtins_string.html
示例代码:
${1.23569?string.percent} ${1.23569?string["0.##"]} ${1.23569?string["0.###"]}
输出:
124% 1.24 1.236
注意:
代码:
<#assign timestamp=1534414202000> ${timestamp?number_to_datetime?string["yyyy/MM/dd HH:mm"]}
输出:
2018/08/16 18:10
示例代码:
<#assign nowTime = .now> ${nowTime} <br /> ${nowTime?string["yyyy/MM/dd HH:mm"]} <br />
输出:
2018-8-16 18:33:50 2018/08/16 18:33
更多内建方法:https://freemarker.apache.org/docs/ref_builtins.html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
主要配置,以下:
## Freemarker 配置 spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.cache=false spring.freemarker.charset=UTF-8 spring.freemarker.check-template-location=true spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.request-context-attribute=request spring.freemarker.suffix=.ftl
配置项 | 类型 | 默认值 | 建议值 | 说明 |
---|---|---|---|---|
spring.freemarker.template-loader-path | String | classpath:/templates/ | 默认 | 模版存放路径 |
spring.freemarker.cache | bool | true | 默认 | 是否开启缓存,生成环境建议开启 |
spring.freemarker.charset | String | - | UTF-8 | 编码 |
spring.freemarker.content-type | String | text/html | text/html | content-type类型 |
spring.freemarker.suffix | String | .ftl | .ftl | 模板后缀 |
spring.freemarker.expose-request-attributes | bool | false | false | 设定全部request的属性在merge到模板的时候,是否要都添加到model中 |
spring.freemarker.expose-session-attributes | bool | false | false | 设定全部HttpSession的属性在merge到模板的时候,是否要都添加到model中. |
spring.freemarker.request-context-attribute | String | - | request | RequestContext属性的名称 |
更多配置:
# FREEMARKER (FreeMarkerProperties) spring.freemarker.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. spring.freemarker.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. spring.freemarker.cache=false # Whether to enable template caching. spring.freemarker.charset=UTF-8 # Template encoding. spring.freemarker.check-template-location=true # Whether to check that the templates location exists. spring.freemarker.content-type=text/html # Content-Type value. spring.freemarker.enabled=true # Whether to enable MVC view resolution for this technology. spring.freemarker.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. spring.freemarker.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. spring.freemarker.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.freemarker.prefer-file-system-access=true # Whether to prefer file system access for template loading. File system access enables hot detection of template changes. spring.freemarker.prefix= # Prefix that gets prepended to view names when building a URL. spring.freemarker.request-context-attribute= # Name of the RequestContext attribute for all views. spring.freemarker.settings.*= # Well-known FreeMarker keys which are passed to FreeMarker's Configuration. spring.freemarker.suffix=.ftl # Suffix that gets appended to view names when building a URL. spring.freemarker.template-loader-path=classpath:/templates/ # Comma-separated list of template paths. spring.freemarker.view-names= # White list of view names that can be resolved.
<html> <head> <title>王磊的博客</title> </head> <body> <div> Hello,${name} </div> </body> </html>
新建index.java文件,Application.java(入口文件)代码不便,index.java代码以下:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/") public class Index { @RequestMapping("/") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("name", "老王"); return modelAndView; } }
关键代码解读:
执行上面4个步骤以后,就能够运行这个Java项目了,若是是IDEA使用默认快捷键“Shift + F10”启动调试,在页面访问:http://localhost:8080/ 就可看到以下效果:
FreeMarker官方文档:https://freemarker.apache.org/
FreeMarker翻译的中文网站:http://freemarker.foofun.cn/toc.html