首页 > 学院 > 开发设计 > 正文

FreeMarker设计指南(3)

2019-11-18 11:24:01
字体:
来源:转载
供稿:网友

3模板

1)整体结构

l         模板使用FTL(FreeMarker模板语言)编写,是下面各部分的一个组合:

Ø         文本:直接输出

Ø         Interpolation:由${和},或#{和}来限定,计算值替代输出

Ø         FTL标记:FreeMarker指令,和Html标记类似,名字前加#予以区分,不会输出

Ø         注释:由<#--和-->限定,不会输出

l         下面是以一个具体模板例子:

<html>[BR]
<head>[BR]
  <title>Welcome!</title>[BR]
</head>[BR]
<body>[BR]
  <#-- Greet the user with his/her name -->[BR]
  <h1>Welcome ${user}!</h1>[BR]
  <p>We have these animals:[BR]
  <ul>[BR]
  <#list animals as being>[BR]
    <li>${being.name} for ${being.PRice} Euros[BR]
  </#list>[BR]
  </ul>[BR]
</body>[BR]
</html>  

l         [BR]是用于换行的非凡字符序列

l         注重事项:

Ø         FTL区分大小写,所以list是正确的FTL指令,而List不是;${name}和${NAME}是不同的

Ø         Interpolation只能在文本中使用

Ø         FTL标记不能位于另一个FTL标记内部,例如:

<#if <#include 'foo'>='bar'>...</if>

Ø         注释可以位于FTL标记和Interpolation内部,如下面的例子:

<h1>Welcome ${user <#-- The name of user -->}!</h1>[BR]
<p>We have these animals:[BR]
<ul>[BR]
<#list <#-- some comment... --> animals as <#-- again... --> being>[BR]
...  

Ø         多余的空白字符会在模板输出时移除

2)指令

l         在FreeMarker中,使用FTL标记引用指令

l         有三种FTL标记,这和HTML标记是类似的:

Ø         开始标记:<#directivename parameters>

Ø         结束标记:</#directivename>

Ø         空内容指令标记:<#directivename parameters/>

l         有两种类型的指令:预定义指令和用户定义指令

l         用户定义指令要使用@替换#,如<@mydirective>...</@mydirective>(会在后面讲述)

l         FTL标记不能够交叉,而应该正确的嵌套,如下面的代码是错误的:

<ul>
<#list animals as being>
  <li>${being.name} for ${being.price} Euros
  <#if use = "Big Joe">
     (except for you)
</#list>
</#if> <#-- WRONG! -->
</ul>  

l         假如使用不存在的指令,FreeMarker不会使用模板输出,而是产生一个错误消息

l         FreeMarker会忽略FTL标记中的空白字符,如下面的例子:

<#list[BR]
  animals       as[BR]
     being[BR]
>[BR]
${being.name} for ${being.price} Euros[BR]
</#list    >  

l         但是,<、</和指令之间不答应有空白字符

3)表达式

l         直接指定值

Ø         字符串

n         使用单引号或双引号限定

n         假如包含非凡字符需要转义,如下面的例子:

${"It's /"quoted/" and
this is a backslash: //"}
 
${'It/'s "quoted" and
this is a backslash: //'} 

输出结果是:

It's "quoted" and
this is a backslash: /
 
It's "quoted" and
this is a backslash: / 

n         下面是支持的转义序列:



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表