简介
FreeMarker 是一款模板引擎:即一种基于模板、用来生成输出文本(任何来自于 HTML格式的文本用来自动生成源代码)的通用工具。
适用场所:HTML页面;代码生成等
指令
if指令
<#if animals.python.price == 0>
Pythons are free today!
</#if>
<#if animals.python.price != 0>
Pythons are free today!
</#if>
<#if animals.python.price < animals.elephant.price>
Pythons are cheaper than elephants today.
</#if>
<#if animals.python.price < animals.elephant.price>
Pythons are cheaper than elephants today.
<#else>
Pythons are not cheaper than elephants today.
</#if>
<#if animals.python.protected>
Warning! Pythons are protected animals!
</#if>
list 指令
<p>We have these animals:
<table border=1>
<tr><th>Name<th>Price
<#list animals as being>
<tr><td>${being.name}<td>${being.price} Euros
</#list>
</table>
<p>And BTW we have these fruits:
<ul>
<#list whatnot.fruits as fruit>
<li>${fruit}
</#list>
<ul>
_index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stus as stu>
<tr>
<td>${stu_index + 1}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.mondy}</td>
</tr>
</#list>
</table>
遍历Map数据
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stuMap?keys as k>
<tr>
<td>${k_index + 1}</td>
<td>${stuMap[k].name}</td>
<td>${stuMap[k].age}</td>
<td >${stuMap[k].mondy}</td>
</tr>
</#list>
</table>
include 指令
使用 include 指令,我们可以在当前的模板中插入其他文件的内容
1、copyright_footer.html
<hr>
<i>
Copyright (c) 2000 <a href="http://www.acmee.com">Acmee
Inc</a>,
<br>
All Rights Reserved.
</i>
2、Index.html
<html>
<head>
<title>Test page</title>
</head>
<body>
<h1>Test page</h1>
<p>Blah blah...
<#include "/copyright_footer.html">
</body>
</html>
空值处理
1、如果user为空,显示Anonymous
<h1>Welcome ${user!"Anonymous"}!</h1>
2、如果user为空,显示
<#if user??><h1>Welcome ${user}!</h1></#if>
3、animals获取内部对象值为空,显示0
<h1>Welcome ${(animals.python.price)!"Anonymous"}!</h1>
4、animals获取内部对象值为空,显示
<#if (animals.python.price)??><h1>Welcome ${animals.python.price}!</h1></#if>
算数运算
${100 – x*x}
${x/2}
${12%10}
75
2.5
2
逻辑操作
<#if x < 12 && color = "green">
We have less than 12 things, and they are green.
</#if>
<#if !hot> <#-- here hot must be a boolean -->
It's not hot.
</#if>
内建函数
一、test 存储”Tom & Jerry”
1、html 字符串中所有的特殊 HTML 字符都需要用实体引用来代替
${test?html}
2、upper_case 字符串的第一个字母变为大写形式,对应lower_case
${test?upper_case?html}
输出:
Tom & Jerry
TOM & JERRY
二、seasons 存储了序列"winter", "spring", "summer", "autumn"
3、size 序列中元素的个数
${seasons?size}
4、cap_first 字符串的第一个字母变为大写形式
${seasons[1]?cap_first} <#-- left side can by any expression -->
${"horse"?cap_first}
输出:
4
Spring
Horse
5、trim 去掉字符串首尾的空格
6、int 数字的整数部分