Apache FreeMarker 用法拾零
2021-08-12 本文已影响0人
程就人生
SpringBoot整合Apache FreeMarker(一) - 简书 (jianshu.com)
上次使用 FreeMarker 已是一年半前,现在又有页面需要生成,翻了翻原来项目里的模板,语法基本忘光。而且只做了如何简单使用的笔记,这次就把最常用的一些语法也写一写,以便备用,翻手册范围太广。
list 集合最常用
<ul>
<#list productList as product>
<li>${product_index+1} ${product.goodsName}</li>
</#list>
</ul>
<!--需要排序时,加个sort_by字段-->
<ul>
<#list productList?sort_by("productName") as product>
<li>${product_index+1} ${product.goodsName}</li>
</#list>
</ul>
<!--如果list集合不存在,直接在循环里加个else即可,不需要单独做判断-->
<#list sequence as item>
Part repeated for each item
<#else>
Part executed when there are 0 items
</#list>
<!--项目的个数-->
${list?size}
productList 是从后台传递过来的list集合;
product_index 用于获取当前索引,从0开始;
非空判断怎么判?
<#if goodsName??>
goodsNamefound
<#else>
No goodsName found
</#if>
?? 两个问号神写法!
上面的示例用到了if,那么多重判断怎么判,多个 if 吗,不需要!
<#if goodsName??>
goodsNamefound
<#elseif goodsName=='aaa' >
aaa
<#else>
No goodsName found
</#if>
如果某个对象的某个属性没有赋值怎么办?
<!--没有赋值,可以设置默认值的,那就设置默认值吧!-->
${product.keysword!''}
默认值可以这样设置,太简洁了吧!
如果想让html标签原样展示怎么做?
${testString?html}
后面加个html轻松搞定。
字符串常用的处理方法
<!--转成大写-->
${testString?upper_case}
<!--转成大写并输出原始html-->
${testString?upper_case?html}
<!--字符串的长度-->
${user?length}
<!--首字母小写,在生成controller类似的class文件时非常有用-->
${testString?uncap_first}
<!--首字母大写 -->
${testString?cap_first}
在模板里定义一个变量,怎么定义?怎么使用?
<!--使用assign关键字定义-->
<#assign x=1 >
${x}
如果定义了一个含有特殊符号的变量,该怎么使用?
<!--定义中包含特殊符号{}-->
<#assign strleft="${">
<#assign strright="}">
//这一段比较特殊,是写在js里面的,原本是想表达 var model=${model},但是又不能直接写成${model},这样在生成时,会被模板解析,所以需要换个写法;
var model = [[${strleft}model${strright}]];
有个date型的日期,直接写会报错,该如何展示?
${significance.publishDate?string("yyyy-MM-dd")}
做分页,要遍历一个数字,怎么遍历?
<#if currentPage == 1 >
<li class="previous_s"><a href="../sp/videoList.html" >上一页</a></li>
<#elseif currentPage gt 1 >
<li class="previous_s"><a href="../sp/videoList${currentPage-1}.html" >上一页</a></li>
</#if>
<#list 0..pageSize-1 as page>
<#if currentPage == page >
<li class="pages_solid">${page+1}</li>
<#elseif page == 0>
<li class="pages_hollow"><a href="../sp/videoList.html" >${page+1}</a></li>
<#else>
<li class="pages_hollow"><a href="../sp/videoList${page}.html" >${page+1}</a></li>
</#if>
</#list>
<#if currentPage lt pageSize-1 >
<li class="next"><a href="../sp/videoList${currentPage+1}.html">下一页</a></li>
</#if>
为了防止大于号,小于号报错,大于号可以用 gt 代替,小于号可以用 lt 代替,很方便吧!
参考文档:
https://freemarker.apache.org/
http://freemarker.foofun.cn/index.html