freemarker是一款免费的java模板引擎,是一种基于模板和数据生成文本(hmlt、电子邮件、配置文件、源代码等)的工具,它不是面向最终用户的,而是一款程序员使用的组件。
freemarker最初设计是用来在mvc模式的web开发中生成html页面的,所以没有绑定servlet或任意web相关的东西上,所以它可以运行在非web应用环境中。
freemarker第一版在1999年未就发布了,2002年初使用javacc(java compiler compiler是一个用java开发的语法分析生成器)重写了freemarker的核心代码,2015年freemarker代码迁移到了apache下。
github地址:https://github.com/apache/freemarker
freemarker模板存储在服务器上,当有用户访问的时候,freemarker会查询出相应的数据,替换模板中的标签,生成最终的html返回给用户,如下图:
基础使用分为3部分,这3部分组成了freemarker:
指令是freemarker用来识别转换的特殊标签,表达式是标签里具体的语法实现,其他部分是一些不好分类的模板。
使用ftl(freemarker template language)标签来调用指令。
指令速览:
下来我们分别来看每个指令对应具体使用。
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://www.lhsxpumps.com/_localhost:8080/ 就可看到如下效果:
freemarker官方文档:https://freemarker.apache.org/
freemarker翻译的中文网站:http://freemarker.foofun.cn/toc.html
如对本文有疑问, 点击进行留言回复!!
springcloud中feign调用处理mybatis-plus Ipage反序列化问题。
Flume 史上最全面的大数据学习第十篇(一) 别再说不知道flume是什么了
网友评论