首页 > 技术文章 > freeMarker随手笔记

GGDong 2019-07-18 16:30 原文

freemarker官网:http://docs.freemarker.cn/

注意:

1.如果标签没有嵌套内容(在开始标签和结束标签之间的内容),那么可以只使用开始标签

(详情:http://freemarker.foofun.cn/dgui_template_valueinsertion.html)

2.插值使用内建函数c(代表''计算机'')是给计算机程序去识别,如:<a href="/shop/productdetails?id=${product.id?c}">Details...</a>

3.如果插值要生成HTML, 那么强烈建议你利用它来阻止跨站脚本攻击和非格式良好的HTML页面,如:

<#escape x as x?html> 

<p>Title: ${book.title}</p>

<p>Description: <#noescape>${book.description}</#noescape></p>

<h2>Comments:</h2>

<#list comments as comment>

<div class="comment"> ${comment} </div>

</#list>

</#escape>

4.布尔值的插值使用:${married?string("yes", "no")}

一.使用

1.对象 -> ${key.property}

2.日期 -> 当前日期和时间:${date?datetime}
自定义日期格式:${date?string("yyyyMM/dd HH:mm:ss")}
(也可以使用FreeMarker的内建函数date,time和datetime来识别,如${lastUpdated?datetime})

3.处理不存在变量
(通过在变量名后面跟着一个 !(叹号)和默认值)
<h1>welcome ${user!"gg"}</h1>

(通过放置 ?? 来询问一个变量是否存在)
<#if user??><h1>welcome ${user}</h1><#/if>

(多级访问)
(animals.python.price)!0 ==> (animals.python.price)??

4.使用内建函数,如:
fruits?jion(",")通过连接所有项,将列表转换为字符串, 在每个项之间插入参数分隔符(比如 "orange,banana")

更多内建函数链接:http://freemarker.foofun.cn/ref_builtins.html

5.替换(方括号)语法,用 [#ftl]来开始模板,如:

[#ftl]

<p>We have these animals:<table border=1><tr><th>Name<th>Price [#list animals as animal] <tr> <td> [#if animal.size == "large"]<b>[/#if] ${animal.name} [#if animal.size == "large"]</b>[/#if] <td>${animal.price} Euros [/#list] </table>

 

二.指令
1.if指令
<#if >
<#elseif >
<#else >
</#if >

2.list指令
(基本用法)
<#list studentList as student>
下标:${student_index}
</#list>

(只有当fruits有值时才循环)
<#list misc.fruits>        <#list misc.fruits as fruit>

  <ul>              <ul>

    <#items as fruit>       =>                  <li>${fruit}

      <li>${fruit}           </ul>

    </#items>                             </#list>

  </ul>

</#list>

(被sep覆盖的部分只有当还有下一项时才会执行,因此最后面没有逗号。else表示水果为0时执行)
<p>Fruits:<#list misc.fruits as fruit>${fruit}<#sep>,<#else>none</#list>

推荐阅读