Velocity

基本语法

  • ”#”用来标识Velocity的脚本语句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等,如:
#if($info.images)
    <img src="$info.images">
#else
    <img src="noPhoto.jpg">
#end
  • ”$”用来标识一个变量,如
$i
$msg.errorNum
  • ”!”用来强制把不存在的变量显示为空白
$!msg
  • 注释,如:
## 这是一行注释,不会输出
#* xxxx
多行注释
xxxx *#

具体语法可参考[官网] (http://velocity.apache.org/engine/devel/user-guide.html)

语法详解

  • 变量赋值输出
Welcome $name to halo9pan.cn!
today is $date.
tdday is $mydae.//未被定义的变量将当成字符串
  • 设置变量值,所有变量都以$开头
#set( $iAmVariable = "good!" )
Welcome $name to halo9pan.cn!
today is $date.
$iAmVariable
  • if,else判断
#set ($admin = "admin")
#set ($user = "user")
#if ($admin == $user)
    Welcome admin! 
#else
    Welcome user!
#end
  • 迭代数据List ($velocityCount为列举序号,默认从1开始)
#foreach( $product in $allProducts ) 
    <li>$velocityCount $product.title</li>
#end
  • 迭代数据get key
#foreach($key in $myProducts.keySet() )
    $key `s value: $myProducts.get($key)
#end
  • 导入其它文件,可输入多个
#parse("vm_a.vm")
#parse("vm_b.vm")
  • 简单遍历多个div
#foreach( $i in [1,2,3,4] )
<div>$i</div>
#end
  • 双引号与单引号
#set ($var="helo")
test"$var" 返回testhello
test'$var' 返回test'$var'

可以通过设置 stringliterals.interpolate=false改变默认处理方式

  • Range
#foreach( $foo in [1..5] )
  • 定义宏macros,相当于函数
#macro( d )
  <tr><td></td></tr>
#end
调用
#d() 
  • 带参数的宏
#macro( tablerows $color $somelist )
  #foreach( $something in $somelist )
  <tr><td bgcolor=$color>$something</td></tr>
  #end
#end

Freemarker

基础语法

  • 变量
data = {
	"user": "halo9pan"	
}
  • 模板
<h1>Hello ${user}</h1>
  • 字符串链接
${"Hello,${user}!"}
${"Hello,"+user+"!"};

${..}只能用于文本部分,下面的代码是错误的:

<#if ${isBig}>Wow!</#if>
<#if "${isBig}">Wow!</#if>

应该写成:

<#if isBig>Wow!</#if>

具体语法可参考[官网] (http://freemarker.incubator.apache.org/docs/index.html)

内建函数

  1. html:对字符串进行HTML编码
  2. cap_first:将字符串第一个字母成大写
  3. lower_case:将字符串转换成小写
  4. upper_case:将字符串转换成大写
  5. trim: 去掉字符串前后的空白字符
  6. size: 获得序列中元素的数目
  7. int 取得数字的整数部分

指令

  • if
data = {
	"user": "halo9pan",
	"isNewGuys": true
}
<h1><#if user == "halo9pan">Your are hero.</#if></h1>
<p>
	<#if isNewGuys>
		new guys!
	<#else>
		old
	</#if>
</p>
  • list
data = [
	{
		"user": "halo9pan",
		"gender": "male"
	},
	{
		"user": "panhao",
		"gender": "male"
	}
]
<ul>
	<#list data as item
	<li>name:${item.user};Gender:${item.gender}</li>
	</#list>
</ul>
  • include
<#include "/xxx.html">
  • 空值的处理
<h1>Welcome ${user!"default"}!</h1>

如果user不存在或者为null,最后模板会输出 default这个值
反之,输出user的真实值!

<#if user??><h1>hello ${user}</h1></#if>

如果,user 存在则输出包括的内容!
反之,则忽略整条模板内容!