1 前言

2 注释

<#-- -->

3 数据类型

3.1 容器

3.1.1 hash表,即键值对

{"Joe":23, "Fred":25} + {"Joe":30, "Julia":18} <#– hash表相加–>

3.1.2 数组

["Joe", "Fred"] + ["Julia", "Kate"] <#– 数组可以相加 –> seq[1..4] 获取index1到4的子数组 seq[1..] 获取index1到最后的子数组

3.1.3

3.2 单个数据类型

3.2.1 字符串

${r"${foo}"} <#– 原生字符串–> 输出为${foo} ${r"C:\ foo\bar"}

3.2.2 数字

3.2.3 布尔类型

3.2.4 日期/时间

4 标签类型

5 函数

5.1 内建函数

test?upper_case?html,内嵌函数可以双重使用
${(x/2)?int} <!– 取得结果中的整数部分–>
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}
user?upper_case <!– 大写形式–>

5.1.1 字符串使用的内建函数:

  1. html: 字符串中所有的特殊 HTML 字符都需要用实体引用来代替(比如<代替&lt;) 。
  2. cap_first:字符串的第一个字母变为大写形式
  3. lower_case:字符串的小写形式
  4. upper_case:字符串的大写形式1
  5. trim:去掉字符串首尾的空格

5.1.2 序列使用的内建函数:

size:序列中元素的个数

5.1.3 数字使用的内建函数:

int:数字的整数部分(比如-1.9?int 就是-1)

5.2 自定义函数

6 变量

6.1 声明

<#assign x = 1> <#--   创建变量  x -- >

6.2 ${}

引用变量

6.2.1 对不存在的变量的处理

不存在的变量包括两种

  1. null
  2. 为空

FreeMarker中对不存在的变量采取严格模式,即除非显式表明,否则一旦遇到就报错。
显式声明的方式:

  1. <h1>Welcome ${user!"Anonymous"}!</h1>::当user不存在时使用Anonymous
  2. user??::如果user不存在,返回false
  3. animals.python.price!0

::如上写法,仅price不存在时使用0,animals、python不存在时仍然报错。
为了防止这种情况,可以这样写(animals.python.price)!0

6.2.2 判断为空否:

<#if (user.group)??>
     不为空
<#else>
     为空
</#if>

6.2.3 <#></>

类似jstl标签,能够执行一些功能,比如逻辑判断,轮询等等

  1. <#if></if>
    <#if animals.python.price == 0>
    Pythons are free today!
    </#if>
    
  2. <#list sequence as loopVariable>repeatThis</#list>
    <#list animals as being>
    <tr><td>${being.name}<td>${being.price} Eurosf
    </#list>
    
  3. <#include "/copyright_footer.html">

6.2.4 <@></>,即自定义标签

用户自定义的指令,类似jsp中的自定义标签。

  1. 标签定义
    <#-- 定义一个名称为 border的标签-->
    <#macro border attributeName="s">
    <h1>${attributeName}</h1>
    <table border=4 cellspacing=0 cellpadding=4><tr><td>
    <#nested><#-- 取得标签体中的内容 -->
    </td></tr></table>
    </#macro>
    
  2. 标签使用
    <@border attributeName="haha">The bordered text</@border>