freemarker全部

                           关于FreeMarker

 

一、  什么是freemarker

FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. FreeMarker是一个模板引擎” ;一个通用工具生成文本输出(东西向的产品和从HTML源代码)基于模板。 FreeMarker is designed to be practical for the generation of HTML Web pages , particularly by servlet-based applications following the MVC (Model View Controller) pattern. The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers. Everybody works on what they are good at.   为实现生成HTML网页 ,特别是通过servlet的应用程序后MVC (模型视图控制器)模式。背后的想法使用MVC模式的动态网页是您单独设计( HTML全文作者)从程序员。每个人都适用于他们所擅长的。 Designers can change the appearance of a page without programmers having to change or recompile code, because the application logic (Java programs) and page design (FreeMarker templates) are separated.设计人员可以改变的外观网页程序员无需更改或重新编译代码,因为应用程序逻辑( Java程序)和网页设计( FreeMarker模板)隔开。 Templates do not become polluted with complex program fragments.模板不会成为污染的复杂程序的碎片。

Although FreeMarker has some programming capabilities, it is not a full-blown programming language like PHP.虽然FreeMarker具有一些编程的能力,它不是一个完全成熟的编程语言一样的PHP Instead, Java programs prepare the data to be displayed (like issue SQL queries), and FreeMarker just generates textual pages that display the prepared data using templates.相反, Java程序编写的数据显示(如SQL查询问题) ,和FreeMarker刚才生成的网页显示文本的编写数据使用的范本。

FreeMarker is not a Web application framework. FreeMarker 不是一个 Web应用框架。 It is suitable as a component in a Web application framework, but the FreeMarker engine itself knows nothing about HTTP or servlets.它适用于作为一个组成部分在一个Web应用框架,但FreeMarker引擎本身一无所知HTTPservlets It simply generates text.它只是生成的文本。 As such, it is perfectly usable in non-web application environments as well.因此,它是完全可在非Web应用环境以及。 Note, however, that we provide out-of-the-box solutions for using FreeMarker as the view component of Model 2 frameworks (eg Struts), which also let you use JSP taglibs in the templates.但是请注意,我们提供了型的解决方案中使用FreeMarker作为视图组件模型2框架(如Struts的) ,这也让您使用的JSP taglibs的模板。 Freemarker 的主要思想是:模板+数据模型=输出。

1.数据模型

 数据模型基本上是树.

 root
  |
  +- animals
  |   |
  |   +- mouse
  |   |   |   
  |   |   +- size = "small"
  |   |   |   
  |   |   +- price = 50
  |   |
  |   +- elephant
  |   |   |   
  |   |   +- size = "large"
  |   |   |   
  |   |   +- price = 5000
  |   |
  |   +- python
  |       |   
  |       +- size = "medium"
  |       |   
  |       +- price = 4999
  |
  +- test = "It is a test"
  |
  whatnot
      |
      +- fruits
          |
          +- (1) = "orange"
          |
          +- (2) = "banana"
变量存储一个单一的价值( size price  name )被称为 
目录(root animals )被称为哈希值
序列 They are similar to hashes, but they don't store names for the variables they contain.是类似的哈希值,Instead, they store the subvariables sequentially, and you can access them with a numerical index.您可以访问它们的数值指标。 For example, in this data-model, animals and whatnot.fruits are sequences:例如,在此数据模型whatnot.fruits[1]的序列

摘要:

·         The data-model can be visualized as a tree.数据可视化模型可作为一个树。

·         Scalars store a single value.标储存单一的价值。 The value can be a string or a number or a date/time or a boolean.此值可以是一个字符串或数字或日期/时间或一个布尔值。

·         Hashes are containers that store other variables and associate them with a unique lookup name.哈希的容器存放其他变数并与一个独特的查询名称。

·         Sequences are containers that store other variables in an ordered sequence.序列容器存放在其他变数排列顺序。 The stored variables can be retrieved via their numerical index, starting from 0.存储变量可以检索通过其数值指标,从0

2.模板

最简单的模板是一个纯HTML文件(或任何文本文件- FreeMarker不仅限于为HTML When the client visits that page, FreeMarker will send that HTML to the client as is.当客户端访问该网页, FreeMarker将发送到用户端的HTML一样。 However if you want that page to be more dynamic then you begin to put special parts into the HTML which will be understood by FreeMarker:但是如果你想该网页将更有活力,那么你开始把部分进入特殊的HTML将理解FreeMarker

·         $ ... FreeMarker将取代它的产出与实际价值的东西在大括号。 They are called interpolation s.他们被称为插值………

·         FTL tags (for FreeMarker Template Language tags): FTL tags are a bit similar to HTML tags, but they are instructions to FreeMarker and will not be printed to the output. FTL 标签(用于FreeMarker模板语言标记) FTL标签有点类似于HTML标记,但它们的指令, FreeMarker并不会被打印输出。 The name of these tags start with # . (User-defined FTL tags use @ instead of # , but they are an advanced topic.)这些标记开始 (用户定义的FTL标签用@代替 

·         Comments: Comments are similar to HTML comments, but they are delimited by <#-- and --> . Anything between these delimiters and the delimiter itself will be ignored by FreeMarker, and will not be written to the output. 注释:评论的HTML类似的评论,但他们划定的<#----> 。任何这些定界符和分隔本身将被忽略的FreeMarker ,并不会写入输出。

FTL 标签:

·         开始标签: <#directivename parameters>

·         结束标签: </#directivename>

 

集合标签:
<#list animals as being>
  <li>${being.name} for ${being.price} Euros
  <#if user == "Big Joe">
     (except for you)
</#list> <#-- WRONG! The "if" has to be closed first. -->
</#if>
</ul>  
赋值标签:
<#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
字符串输出: ${...}

二、  怎么用freemarker

1创建配置实例

首先,必须创建一个freemarker.template.Configuration实例,并调整其设置。 A Configuration instance is a central place to store the application level settings of FreeMarker. 配置实例是一个中心位置来存储应用程序级别设置FreeMarker Also, it deals with the creation and caching of pre-parsed templates.此外,它涉及建立和缓存预解析模板。 Probably you will do it only once at the beginning of the application (possibly servlet) life-cycle:也许你会做到这一点只有一次开始的时候,应用程序(可能的servlet )生命周期:

Configuration cfg = new Configuration();
// Specify the data source where the template files come from.
// Here I set a file directory for it:
cfg.setDirectoryForTemplateLoading(new File("模板路径"));

//cfg.setServletContextForTemplateLoading(this.getServletContext(), "模板路径");

//cfg.setClassForTemplateLoading(this.class,” 模板路径”)

// Specify how templates will see the data-model. This is an advanced topic...
// but just use this:
cfg.setObjectWrapper(new DefaultObjectWrapper()); 
2创建数据模型

在简单的情况下,您可以建立数据模型使用java.langjava.util定制的Java类和Bean

·         Use java.lang.String for strings.使用构造函数的字符串。

·         Use java.lang.Number descents for numbers.使用java.lang.Number的数字。

·         Use java.lang.Boolean for boolean values.使用java.lang.BooleanBoolean值。

·         Use java.util.List or Java arrays for sequences.使用java.util.ListJavaarrays

·         Use java.util.Map for hashes.使用java.util.Map的哈希。

·         Use your custom bean class for hashes where the items correspond to the bean properties.使用您自定义的bean类哈希的项目相对应的bean属性。 For example the price property of product can be get as product.price .例如知识产权的产品的价格可以得到作为product.price (The actions of the beans can be exposed as well; see much later here )

(root)
  |
  +- user = "Big Joe"
  |
  +- latestProduct
      |
      +- url = "products/greenmouse.html"
      |
      +- name = "green mouse"  
 
 
// Create the root hash
Map root = new HashMap();
// Put string ``user'' into the root
root.put("user", "Big Joe");
// Create the hash for ``latestProduct''
Map latest = new HashMap();
// put ``url'' and ``name'' into latest
 
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse"); 
// and put it into the root 
root.put("latestProduct", latest);
3获取模板

模板是由freemarker.template.Template情况。 Typically you obtain a Template instance from the Configuration instance.通常你获得模板实例从Configuration实例。 Whenever you need a template instance you can get it with its getTemplate method.当你需要一个模板例如你可以用它getTemplate方法。 Store the example template in the test.ftl file of the earlier set directory, then you can do this: test.ftl文件早先设定的目录,那么你可以Template temp = cfg.getTemplate("test.ftl");

When you call this, it will create a Template instance corresponds to test.ftl , by reading /where/you/store/templates/ test.ftl and parsing (compile) it.它会创建一个Template实例对应于test.ftl ,通过阅读 模板路径/test.ftl和解析它。 The Template instance stores the template in the parsed form, and not as text.Template实例存储的模板中的解析形式,而不是文字。 Configuration caches Template instances, so when you get test.ftl again, it probably will not create new Template instance (thus doesn't read and parse the file), just returns the same instance as for the first time.Configuration缓存Template实例,因此当你再次解析test.ftl,它可能不会创建新的Template实例,只需返回同一例如,第一次。

4. 合并模板与数据模型

数据模型+模板=输出,我们有一个数据模型和模板 ,所以获得的产出,我们必须将它们合并。 This is done by the process method of the template.

Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();  

//PrintWriter p = new PrintWriter(new FileOutputStream(new File("1.html")));//如果为servelet    response.getOutputStream()

// temp.process(root, p); This will print to your terminal the output what you have seen in the first example of the Template Author's Guide. Once you have obtained a Template instance, you can merge it with different data-models for unlimited times ( Template instances are basically stateless).

import freemarker.template.*;
import java.util.*;
import java.io.*;
 
全部代码:
public class Test {
 
    public static void main(String[] args) throws Exception {
        
        /* ------------------------------------------------------------------- */    
        /* You usually do it only once in the whole application life-cycle:    */    
    
        /* Create and adjust the configuration */
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(
                new File("/where/you/store/templates"));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
 
        /* ------------------------------------------------------------------- */    
        /* You usually do these for many times in the application life-cycle:  */    
                
        /* Get or create a template */
        Template temp = cfg.getTemplate("test.ftl");
 
        /* Create a data-model */
        Map root = new HashMap();
        root.put("user", "Big Joe");
        Map latest = new HashMap();
        root.put("latestProduct", latest);
        latest.put("url", "products/greenmouse.html");
        latest.put("name", "green mouse");
 
        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
        out.flush();
    }

三、  格式化,strust标签,JSTL标签,传值范围.

日期

 

string(当和一个日期值一起使用)

这个内置标签用指定的格式把日期转换成字符串,(把默认的格式用FreeMarkerate_format,time_formatdatetime_format设置指定对你有好处,那样的话你就不需要这个标签了。

格式可以是一个预定义的,你也可以明确指定格式。

预定义的格式是:shortmediumlongfull。定义了结果字符串的长度。例如,如果localeUS_EN,时区是US.PACIFIC,那么:

${openingTime?string.short}
${openingTime?string.medium}
${openingTime?string.long}
${openingTime?string.full}

${nextDiscountDay?string.short}
${nextDiscountDay?string.medium}
${nextDiscountDay?string.long}
${nextDiscountDay?string.full}

${lastUpdated?string.short}
${lastUpdated?string.medium}
${lastUpdated?string.long}
${lastUpdated?string.full}

输出类似这样:

  
12:45 PM
12:45:09 PM
12:45:09 PM CEST
12:45:09 PM CEST

4/20/07
Apr 20, 2007
April 20, 2007
Friday, April 20, 2007

4/20/07 12:45 PM
Apr 20, 2007 12:45:09 PM
April 20, 2007 12:45:09 PM CEST
Friday, April 20, 2007 12:45:09 PM CEST

short,medium.longfull准确的意思依赖于当前locale(语言),此外,这是你运行FreeMarkerjava实现平台所指定的,而不是FreeMarker

对于即包含日期和时间的日期值,你可以单独的指定日期和时间部分的长度。

${lastUpdated?string.short_long} <#-- short date, long time -->
${lastUpdated?string.medium_short} <#-- medium date, short time -->


将会输出:

   4/8/03 9:24:44 PM PDT
Apr 8, 2003 9:24 PM


注意:string.short?string.short_short是一样的,?string.mediumstring.medium_medium一样……

警告:

不幸的是,由于java平台的限制。当你在Data Model中存有日期值的时候,FreeMarker不能决定该变量只存储日期部分或者时间部分再或者日期和时间。这种情况下当你像${lastUpdated?string.short}或者简单的${lastUpdated}这样写的时候,FreeMarker不知道如何显示日期。这样它会停下来,并且报错。为了防止这样,你可以使用?date,?time?datetime内置标签来帮助FreeMarker。举例:${lastUpdated?datetime?string.short}.询问程序员某个日期变量是否存在这个问题,或者一直使用?date,?time?datetime

你可以使用?string(格式)明确指定格式,代替预定义格式。格式使用java日期格式语法例如:

${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}
${lastUpdated?string("EEE, MMM d, ''yy")}
${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")}


将会输出:

2003-04-08 21:24:44 Pacific Daylight Time
Tue, Apr 8, '03
Tuesday, April 08, 2003, 09:24:44 PM (PDT)


注意:

不像预定义格式,你不需要在指定的格式上使用?date,?time?datetime,因为你指定的格式告诉FreeMarKer显示日期的哪部分。无论如何,FreeMarker都会相信你,so you can show "noise" if you display parts that are actually not stored in the variable.例如:${openingTime?string("yyyy-mm-dd hh:mm:ss a")},openingTime只存储了时间。将会显示1790-01-01 09:24:44 PM.

格式也可以是short,medium……"short_medium"等等。这样跟你用"."使用预定义的格式是一样的:someDate?string("short")和someDate?string.short是相当的。

date,time,datetime

这些标签可以用来指定日期变量中的哪些部分被使用。

date:只使用年、月、日

time:只使用时、分、秒和毫秒部分

datetime:日期和时间两部分都被使用

理想情况下,你不需要使用它们。不幸的是,由于java平台的技术限制。FreeMarker有的时候不能找到日期变量使用的部分(例如:只有年月日,或者只有时分秒,或者两者)询问程序员那个变量存在这个问题。如果FreeMarker需要执行一个需要这个变量的操作--就像把日期作为字符显示--但是它不知道使用那些部分,它会停下来报错。这就是你必须使用这些标签的情况。例如:假定openingTime就是这样一个问题变量:

<#assign x = openingTime> <#-- no problem can occur here -->
${openingTime?time} <#-- without ?time it would fail -->
<#-- For the sake of better understanding, consider this: -->
<#assign openingTime = openingTime?time>
${openingTime} <#-- this will work now -->


另一种用法:切短日期。例如:

Last updated: ${lastUpdated} <#-- assume that lastUpdated is a date-time value -->
Last updated date: ${lastUpdated?date}
Last updated time: ${lastUpdated?time}


将显示:

Last updated: 04/25/2003 08:00:54 PM
Last updated date: 04/25/2003
Last updated time: 08:00:54 PM

数字

把一个数字转换成字符串时,使用的java语言使用的数字格式(Locale相关),这样是为了符合人类的习惯.比如300000会显示成300,000.如果我们把这个数字作为表单的一个域值放进数据库或者在javascript中使用时,需要再转换成适合计算机输入的格式.这个标签用来输出数字(例如用${x?c}替换${x})防止这种格式转换.

string(当跟一个数字一起使用时)
将一个数字转换成字符传,使用默认的格式,当然也可以明确的要使用的指定数字或者日期格式.
3中预置格式:number,currency,percent.你可以像下面一样使用表达式:

<#assign answer=42/>
${answer}
${answer?string}  <#-- the same as ${answer} -->
${answer?string.number}
${answer?string.currency}
${answer?string.percent} 

 

 

如果使用的是的US 英语,输出是

42
42
42
$42.00
4,200%

输出前3个是一样的,因为前2个使用默认的格式,在这里是"number".你可以改变默认设置

<#setting number_format="currency"/>
<#assign answer=42/>
${answer}
${answer?string}  <#-- the same as ${answer} -->
${answer?string.number}
${answer?string.currency}
${answer?string.percent} 

将会输出:

$42.00
$42.00
42
$42.00
4,200% 

 


除了3种预置的格式,你还可以使用java小数格式化语法,即可以像预置格式一样使用,也可以像明确的格式选择器:

<#setting number_format="0.###E0"/>
${1234}
${12345?string("0.####E0")}  

输出:

1.234E3
1.2345E4  

注意:你也可以${answer?string("number")}${answer?string.number}.是一样的。

注意:数字格式是LOCALE敏感的:

<#setting locale="en_US">
US people writes:        ${12345678?string(",##0.00")}
<#setting locale="hu">
Hungarian people writes: ${12345678?string(",##0.00")}  

输出:

US people writes:        12,345,678.00
Hungarian people writes: 12 345 678,00  

 

3标签

<#assign html=JspTaglibs["/WEB-INF/struts-html.tld"]>

<#assign bean= JspTaglibs["/WEB-INF/struts-bean.tld"]>

<#assign logic=JspTaglibs["/WEB-INF/struts-logic.tld"]>

<#assign c= JspTaglibs["/WEB-INF/c.tld"]>

. <@logic.iterate name="m" id="x" indexId="index">

     <@bean.write name="x" property="userName"/>

  /@logic.iterate

 

 

4作用域

    ${Request.user.userName} 

     ${Session.user}

 

 

 

 

 

 

四、  其他

Freemarker API 地址:http://freemarker.sourceforge.net/docs/api/index.html

Freemarker 使用手册地址:http://freemarker.sourceforge.net/docs/index.html

                                                                                

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JAVA模版引擎Freemarker常用标签(一) 1. if指令 这是一个典型的分支控制指令,该指令的作用完全类似于Java语言中的if,if指令的语法格式如下: <#if condition>... <#elseif condition>... <#elseif condition>... <#else> ... </#if> 例子如下: <#assign age=23> <#if (age>60)>老年人 <#elseif (age>40)>中年人 <#elseif (age>20)>青年人 <#else> 少年人 </#if> 输出结果是:青年人 上面的代码中的逻辑表达式用括号括起来主要是因为里面有>符号,由于FreeMarker会将>符号当成标签的结束字符,可能导致程序出错,为了避免这种情况,我们应该在凡是出现这些符号的地方都使用括号. <#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#else> Pythons are not cheaper than elephants today. </#if> 2、 switch , case , default , break指令 这些指令显然是分支指令,作用类似于Java的switch语句,switch指令的语法结构如下: <#switch value> <#case refValue>...<#break> <#case refValue>...<#break> <#default>... </#switch> 3、 list, break指令 list指令是一个迭代输出指令,用于迭代输出数据模型中的集合,list指令的语法格式如下: <#list sequence as item> ... </#list> 上面的语法格式中,sequence就是一个集合对象,也可以是一个表达式,但该表达式将返回一个集合对象,而item是一个任意的名字,就是被迭代输出的集合元素.此外,迭代集合对象时,还包含两个特殊的循环变量: item_index:当前变量的索引值 item_has_next:是否存在下一个对象 也可以使用<#break>指令跳出迭代 例子如下: <#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as x> ${x_index + 1}.${x}<#if x_has_next>,</if> <#if x="星期四"><#break></#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>We have these animals: <table border=1> <tr><th>Name<th>Price <tr><td>mouse<td>50 Euros <tr><td>elephant<td>5000 Euros <tr><td>python<td>4999 Euros </table> 4、include指令 include指令的作用类似于JSP的包含指令,用于包含指定页.include指令的语法格式如下: <#include filename [options]> 在上面的语法格式中,两个参数的解释如下: filename:该参数指定被包含的模板文件 options:该参数可以省略,指定包含时的选项,包含encoding和parse两个选项,其中encoding指定包含页面时所用的解码集,而parse指定被包含文件是否作为FTL文件来解析,如果省略了parse选项值,则该选项默认是true. <html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> <p>Blah blah... <#include "/copyright_footer.html"> </body> </html> 5、 import指令 该指令用于导入FreeMarker模板中的所有变量,并将该变量放置在指定的Map对象中,import指令的语法格式如下: <#import "/lib/common.ftl" as com> 上面的代码将导入/lib/common.ftl模板文件中的所有变量,将这些变量放置在一个名为com的Map对象中. 创建库 ? 下面是一个创建库的例子(假设保存在lib/my_test.ftl中): <#macro copyright date> <p>Copyright (C) ${date} Julia Smith. All rights reserved. <br>Email: ${mail}</p> </#macro> <#assign mail = "jsmith@acme.com"> ? 使用import指令导入库到模板中,Freemarker会为导入的库创建新的名字空间,并可以通过import指令中指定的散列变量访问库中的变量: <#import "/lib/my_test.ftl" as my> <#assign mail="fred@acme.com"> <@my.copyrightdate="1999-2002"/> ${my.mail} ${mail} 输出结果: <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved. <br>Email: jsmith@acme.com</p> jsmith@acme.com fred@acme.com 可以看到例子中使用的两个同名变量并没有冲突,因为它们位于不同的名字空间 l 可以使用assign指令在导入的名字空间中创建或替代变量,下面是一个例子: <#import "/lib/my_test.ftl" as my> ${my.mail} <#assign mail="jsmith@other.com" in my> ${my.mail} l 输出结果: jsmith@acme.com jsmith@other.com l 数据模型中的变量任何地方都可见,也包括不同的名字空间,下面是修改的库: <#macro copyright date> <p>Copyright (C) ${date} ${user}. All rights reserved.</p> </#macro> <#assign mail = "${user}@acme.com"> l 假设数据模型中的user变量的值是Fred,则下面的代码: <#import "/lib/my_test.ftl" as my> <@my.copyright date="1999-2002"/> ${my.mail} l 输出结果: <p>Copyright (C) 1999-2002 Fred. All rights reserved.</p> 1.6 算术运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , % 看如下的代码: <#assign x=5> ${ x * x - 100 } ${ x /2 } ${ 12 } 输出结果是: -75 2.5 2 在表达式中使用算术运算符时要注意以下几点: 1,运算符两边的运算数字必须是数字 2,使用+运算符时,如果一边是数字,一边是字符串,就会自动将数字转换为字符串再连接,如:${3 + "5"},结果是:35 使用内建的int函数可对数值取整,如: <#assign x=5> ${ (x/2)?int } ${ 1.1?int } ${ 1.999?int } ${ -1.1?int } ${ -1.999?int } 结果是:2 1 1 -1 -1 1.7 比较运算符 表达式中支持的比较运算符有如下几个: 1. =或者==:判断两个值是否相等. 2. !=:判断两个值是否不等. 3. >或者gt:判断左边值是否大于右边值 4. >=或者gte:判断左边值是否大于等于右边值 5. <或者lt:判断左边值是否小于右边值 6. <=或者lte:判断左边值是否小于等于右边值 注意:=和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比 较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)> 1.8 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误 1.9 内建函数 FreeMarker还提供了一些内建函数来转换输出,可以在任何变量后紧跟?,?后紧跟内建函数,就可以通过内建函数来轮换输出变量.下面是常用的内建的字符串函数: html:对字符串进行HTML编码 cap_first:使字符串第一个字母大写 lower_case:将字符串转换成小写 upper_case:将字符串转换成大写 trim:去掉字符串前后的空白字符 下面是集合的常用内建函数 size:获取序列中元素的个数 下面是数字值的常用内建函数 int:取得数字的整数部分,结果带符号 例如: <#assign test="Tom & Jerry"> ${test?html} ${test?upper_case?html} 结果是:Tom & Jerry TOM & JERRY 1.10 空值处理运算符 FreeMarker对空值的处理非常严格,FreeMarker的变量必须有值,没有被赋值的变量就会抛出异常,因为FreeMarker未赋值 的变量强制出错可以杜绝很多潜在的错误,如缺失潜在的变量命名,或者其他变量错误.这里所说的空值,实际上也包括那些并不存在的变量,对于一个Java的 null值而言,我们认为这个变量是存在的,只是它的值为null,但对于FreeMarker模板而言,它无法理解null值,null值和不存在的变 量完全相同. 为了处理缺失变量,FreeMarker提供了两个运算符: !: 指定缺失变量的默认值 ??: 判断某个变量是否存在 其中,!运算符的用法有如下两种: variable!或variable!defaultValue,第一种用法不给缺失的变量指定默认值,表明默认值是空字符串,长度为0的集合,或者长度为0的Map对象. 使用!指定默认值时,并不要求默认值的类型和变量类型相同.使用??运算符非常简单,它总是返回一个布尔值,用法为:variable??,如果该变量存在,返回true,否则返回false ########################### 最常用的概念 1、 scalars:存储单值 字符串:简单文本由单或双引号括起来。 数字:直接使用数值。 日期:通常从数据模型获得 布尔值:true或false,通常在<#if …>标记中使用 2、 hashes:充当其它对象的容器,每个都关联一个唯一的查询名字 具有一个唯一的查询名字和他包含的每个变量相关联。 3、 sequences:充当其它对象的容器,按次序访问 使用数字和他包含的每个变量相关联。索引值从0开始。 4、 集合变量: 除了无法访问它的大小和不能使用索引来获得它的子变量:集合可以看作只能由<#list...>指令使用的受限sequences。 5、 方法:通过传递的参数进行计算,以新对象返回结果 方法变量通常是基于给出的参数计算值在数据模型中定义。 6、 用户自定义FTL指令:宏和变换器 7、 节点 节点变量表示为树型结构中的一个节点,通常在XML处理中使用。 在模板里对sequences和hashes初始化 sequences 1. [“you”,”me”,”he”] 2. 1..100 3. [ {“Akey”:”Avalue”},{“Akey1”:”Avalue1”}, {“Bkey”:”Bvalue”},{“Bkey1”:”Bvalue1”}, ] hashes {“you”:”a”,”me”:”b”,”he”:”c”} 注释标志 <#-- 这里是注释 --> 旧版本的freemarker采用的是<#comment> 注释 </#comment>方法 sequences内置方法 sequence?first 返回sequence的第一个值;前提条件sequence不能是null sequence?last 返回sequence最后一个值 sequence?reverse 反转sequence的值 sequence?size 返回sequence的大小 sequence?sort 对sequence按里面的对象toString()的结果进行排序 sequence?sort_by(value) 对sequence 按里面的对象的属性value进行排序 如: sequence里面放入的是10 个user对象,user对象里面包含name,age等属性 sequence?sort_by(name) 表示所有的user按user.name进行排序 hashes内置方法 hash?keys 返回hash里的所有keys, 返回结果类型sequence hash?values 返回hash里的所有value, 返回结果类型sequence 模板 使用FTL(freeMarker模板语言)编写 组成部分 一、整体结构 1、注释:<#--注释内容-->,不会输出。 2、文本:直接输出。 3、interpolation:由 ${var} 或 #{var} 限定,由计算值代替输出。 4、FTL标记 二.表达式 1、直接指定值: 1-1、字符串: 由双引号或单引号括起来的字符串,其中的特殊字符(如' " \等)需要转义。 1-2、raw字符串: 有一种特殊的字符串称为raw字符串,被认为是纯文本,其中的\和{等不具有特殊含义,该类字符串在引号前面加r,下面是一个例子: ${r"/${data}"year""}屏幕输出结果为:/${data}"year" 转义 含义 序列 \" 双引号(u0022) \' 单引号(u0027) \\ 反斜杠(u005C) \n 换行(u000A) \r Return (u000D) \t Tab (u0009) \b Backspace (u0008) \f Form feed (u000C) \l < \g > \a & \{ { \xCode 4位16进制Unicode代码 1-3、数字:直接输入,不需要引号 1)、精度数字使用“.”分隔,不能使用分组符号 2)、目前版本不支持科学计数法,所以“1E3”是错误的 3)、不能省略小数点前面的0,所以“.5”是错误的 4)、数字8、+8、08和8.00都是相同的 1-4、布尔值:true和false,不使用引号 1-5、序列:由逗号分隔的子变量列表,由[]方括号限定。 1)、子变量列表可以是表达式 2)、可以使用数字范围定义数字序列,不需要方括号限定,例如2..5等同于[2, 3, 4, 5],但是更有效率,可以定义反递增范围如:5..2。 1-6、散列(hash) 1)、由逗号分隔的键/值列表,由{}大括号限定,键和值之间用冒号分隔,如:{"key1":valu1,"key2":"character string"....} 2)、键和值都是表达式,但是键必须是字符串。 2、获取变量: 2-1、顶层变量:${变量名} 变量名只能是字母、数字、下划线、$、#、@ 的组合,且不能以数字开头。 2-2、散列:有两种方法 1)、点语法:变量名字和顶层变量的名字受同样的限制 2)、方括号语法:变量名字无限制,可以是任意的表达式的结果 book.author.name book.author.["name"] book["author"].name book["author"]["name"] 以上是等价的。 2-3、序列:使用散列的方括号语法获取变量,方括号中的表达式结果必须为数字。注意:第一个项目的索引为0。可以使用 [startindex..endindex]语法获取序列片段。 2-4、特殊变量:FreeMarker内定义变量,使用.variablename语法访问。 3、字符串操作 3-1、interpolation:使用${}或#{}在文本部分插入表达式的值,例如: ${"hello${username}!"} ${"${username}${username}${username}"} 也可以使用+来获得同样的结果: ${"hello"+username+"!"} ${username+username+username} 注意:${}只能用于文本部分而不能出现于标记内。 <#if ${user.login}>或<#if "${user.login}">都是错误的; <#if user.login>是正确的。 本例中user.login的值必须是布尔类型。 3-2、子串: 举例说明:假如user的值为"Big Joe" ${user[0]}${user[4]}结果是:BJ ${user[1..4]}结果是:ig J 4、序列操作 4-1、连接操作:可以使用+来操作,例如: ["title","author"]+["month","day"] 5、散列操作 5-1、连接操作:可以使用+来操作,如果有相同的KEY,则右边的值会替代左边的值,例如: {"title":散列,"author":"emma"}+{"month":5,"day":5}+{"month":6}结果month的值就是6。 6、算术运算 6-1、操作符:+、-、*、/、% 除+号以外的其他操作符两边的数据,必须都是数字类型。 如果+号操作符一边有一个字符型数据,会自动将另一边的数据转换为字符型数据,运算结果为字符型数据。 6-2、比较操作符: 1}、= 2}、== 3}、!= 4}、< 5}、<= 6}、> 7}、>= 1-3的操作符,两边的数据类型必须相同,否则会产生错误 4-7的操作符,对于日期和数字可以使用,字符串不可以使用。 注意: 1}、FreeMarker是精确比较,所以"x" "x " "X"是不等的。 2}、因为<和>对FTL来说是开始和结束标记,所以,可以用两种方法来避免这种情况: 一种是使用括号<#if (a<b)> 另一是使用替代输出,对应如下: < lt <= lte > gt >= gte 6-3、逻辑操作符:只能用于布尔值,否则会出现错误。 &&(and)与运算 ||(or)或运算 !(not)非运算 6-4、内建函数:使用方法类似于访问散列的子变量,只是使用?代替.例如:${test?upper_case?html} 常用的内建函数列举如下: 1}、字符串使用: html:对字符串进行HTML编码 cap_first:字符串第一个字母大写 lower_first:字符串第一个字母小写 upper_case:将字符串转换成大写 trim:去掉字符前后的空白字符 2)、序列使用: size:获得序列中元素的数目 3)、数字使用: int:取得数字的整数部分 7、操作符的优先顺序: 后缀:[subbarName][subStringRange].(mathodParams) 一元:+expr、-expr、! (not) 内建:? 乘法:*、/、% 加法:+、- 关系:<、<=、>、>= (lt、lte、gt、gte) 相等:=、==、!= 逻辑与:&& (and) 逻辑或:|| (or) 数字范围:.. 四、interpolation inperpolation只能用于文本,有两种类型:通用interpolation及数字interpolation 1、通用interpolation 如${expr} 1-1、插入字符串值:直接输出表达式结果。 1-2、插入数字值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: <#setting number_format="currency" /> <#assign answer=42 /> ${answer} <#-- ¥42.00 --> ${answer?string} <#-- ¥42.00 --> ${answer?string.number} <#-- 42 --> ${answer?string.currency} <#-- ¥42.00 --> ${answer?string.percent} <#-- 42,00% --> 1-3、插入日期值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: ${lastupdata?string("yyyy-MM-dd HH:mm:ss zzzz")} <#-- 2003-04-08 21:24:44 Pacific Daylight Time --> ${lastupdata?string("EEE,MMM d, ''yy")} <#-- tue,Apr 8, '03 --> ${lastupdata?string("EEEE,MMMM dd, yyyy,hh:mm:ss a '('zzz')'")} <#-- Tuesday,April 08, 2003, 09:24:44 PM (PDT)--> 1-4、插入布尔值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: <#assign foo=ture /> ${foo?string("yes","no")} <#-- yes --> 2、数字interpolation: 有两种形式: 1)、#{expr} 2)、#{expr;format}:format可以用来格式化数字,format可以是如下: mX:小数部分最小X位 MX:小数部分最大X位 例如: <#assign x=2.582 /> <#assign y=4 /> #{x;M2} <#-- 2.58 --> #{y;M2} <#-- 4 --> #{x;m1} <#-- 2.582 --> #{y;m1} <#-- 4.0 --> #{x;m1M2} <#-- 2.58 --> #{y;m1M2} <#-- 4.0 --> 宏 宏和变换器变量是两种不同类型的用户自定义指令,他们的区别是: 宏可以在模板中用macro指令来定义 变换器是在模板外由程序定义 1、宏:和某个变量关联的模板片段,以便在模板中通过用户自定义指令使用该变量 1-1、基本用法: 例如: <#macro greet> <font size="+2"> Hello JOE! </#macro> 使用时: <@greet></@greet> 如果没有体内容也可以用 <@greet /> 1-2、变量: 1)、可以在宏定义之后定义参数,宏参数是局部变量,只在宏定义中有效。如: <#macro greet person> <font size="+2"> Hello ${person}! </#macro> 使用时: <@greet person="emma"> and <@greet person="LEO"> 输出为: <font size="+2"> Hello emma! <font size="+2"> Hello LEO! 注意:宏的参数是FTL表达式,所以,person=emma和上面的例子中具有不同的意义,这意味着将变量emma的值传给person,这个值可能是任意一种数据类型,甚至是一个复杂的表达式。 宏可以有多个参数,使用时参数的次序是无关的,但是只能使用宏中定义的参数,并且对所有参数赋值。如: <#macro greet person color> <font size="+2" color="${color}"> Hello ${person}! </#macro> 使用时: <@greet color="black" person="emma" />正确 <@greet person="emma" />错误,color没有赋值,此时,如果在定义宏时为color定义缺省值<#macro greet person color="black">这样的话,这个使用方法就是正确的。 <@greet color="black" person="emma" bgcolor="yellow" />错误,宏greet定义中未指定bgcolor这个参数 2、嵌套内容: 2-1、自定义指令可以有嵌套内容,使用<#nested>指令,执行自定义指令开始和结束标记之间的模板片段。例如: <#macro greet> <#nested> </#macro> <@greet>hello Emma!</@greet> 输出为 hello Emma! 2-2、<#nested>指令可以被多次调用,例如 <#macro greet> <#nested> <#nested> <#nested> <#nested> </#macro> <@greet>hello Emma!</@greet> 输出为 hello Emma! hello Emma! hello Emma! hello Emma! 2-3、嵌套的内容可以是有效的FTL,例如: <#macro welcome> <#nested> </#macro> <#macro greet person color="black"> <font size="+2" color="${color}"> Hello ${person}! </#macro> <@welcome> <@greet person="Emma" color="red" /> <@greet person="Andrew" /> <@greet person="Peter" /> </@welcome> 输出为: <font size="+2" color="red"> Hello Emma! <font size="+2" color="black"> Hello Andrew! <font size="+2" color="black"> Hello Peter! 2-4、宏定义中的局部变量对嵌套内容是不可见的,例如: <#macro repeat count> <#local y="test" /> <#list 1..count as x> ${y}${count}/${x}:<#nested /> </#list> </#macro> <@repeat count=3> ${y?default("?")} ${x?default("?")} ${count?default("?")} </@repeat> 输出结果为 test 3/1:??? test 3/2:??? test 3/3:??? 2-5、在宏定义中使用循环变量,通常用来重复嵌套内容,基本用法为:作为nested指令的参数,传递循环变量的实际值,而在调用自定义指令时,在标记的参数后面指定循环变量的名字。 例如: <#macro repeat count> <#list 1..count as x> <#nested x,x/2,x==count /> </#list> </#macro> <@repeat count=4;c,halfc,last> ${c}. ${halfc} <#if last> last! </#if> </@repeat> 输出结果是 1. 0.5 2. 1 3. 1.5 4. 2last! 注意:指定循环变量的数目和用户定义指令开始标记指定的不同不会有问题 调用时,少指定循环变量,多指定的值会不见 调用时,多指定循环变量,多余的循环变量不会被创建 二、在模板中定义变量 1、在模板中定义的变量有三种类型 1-1、plain变量:可以在模板的任何地方访问,包括使用include指令插入的模板,使用assign指令创建和替换。 1-2、局部变量:在宏定义体中有效,使用local指令创建和替换。 1-3、循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建。 注意: 1)、宏的参数是局部变量,不是循环变量。 2)、局部变量隐藏同名的plain变量 3)、循环变量隐藏同名的plain变量和局部变量。 例如: <#assign x="plain"> 1. ${x} <#-- plain --> <@test /> 6. ${x} <#list ["loop"] as x> 7. ${x} <#-- loop --> <#assign x="plain2"> 8. ${x} <#-- loop --> </#list> 9. ${x} <#-- plain2 --> <#macro test> 2. ${x} <#-- plain --> <#local x="local"> 3. ${x} <#-- local --> <#list ["loop"] as x> 4. ${x} <#-- loop --> </#list> 5. ${x} <#-- local --> </#macro> 4)、内部循环变量隐藏同名的外部循环变量 <#list ["loop1"] as x> ${x} <#-- loop1 --> <#list ["loop2"] as x> ${x} <#-- loop2 --> <#list ["loop3"] as x> ${x} <#-- loop3 --> </#list> ${x} <#-- loop2 --> </#list> ${x} <#-- loop1 --> </#list> 5)、模板中的变量会隐藏数据模型中的同名变量,如果需访问数据模型中的变量,使用特殊变量global。 例如: 假设数据模型中的user值为Emma <#assign user="Man"> ${user} <#-- Man --> ${.global.user} <#-- Emma --> macro, nested, return 语法 <#macro name param1 param2 ... paramN> ... <#nested loopvar1, loopvar2, ..., loopvarN> ... <#return> ... </#macro> 用例 <#macro test foo bar="Bar"[A1] baaz=-1> Test text, and the params: ${foo}, ${bar}, ${baaz} </#macro> <@test foo="a" bar="b" baaz=5*5-2/> <@test foo="a" bar="b"/> <@test foo="a" baaz=5*5-2/> <@test foo="a"/> 输出 Test text, and the params: a, b, 23 Test text, and the params: a, b, -1 Test text, and the params: a, Bar, 23 Test text, and the params: a, Bar, -1 定义循环输出的宏 <#macro list title items> ${title?cap_first}: <ul> <#list items as x> <li>${x?cap_first} </#list> </#macro> <@list items=["mouse", "elephant", "python"] title="Animals"/> 输出结果 Animals: 包含body的宏 <#macro repeat count> <#list 1..count as x> <#nested x, x/2, x==count> </#list> </#macro> <@repeat count=4 ; c halfc last> ${c}. ${halfc} <#if last> Last!</#if> </@repeat> 输出 1. 0.5 2. 1 3. 1.5 4. 2 Last! t, lt, rt 语法 <#t> 去掉左右空白和回车换行 <#lt>去掉左边空白和回车换行 <#rt>去掉右边空白和回车换行 <#nt>取消上面的效果 B指令 freemarker指令有两种: 1、预定义指令:引用方式为<#指令名称> 2、用户定义指令:引用方式为<@指令名称>,引用用户定义指令时须将#换为@。 注意:如果使用不存在的指令,FreeMarker不会使用模板输出,而是产生一个错误消息。 freemarker指令由FTL标记来引用,FTL标记和HTML标记类似,名字前加#来加以区分。如HTML标记的形式为<h1></h1>则FTL标记的形式是<#list></#list>(此处h1标记和list指令没有任何功能上的对应关系,只是做为说明使用一下)。 有三种FTL标记: 1)、开始标记:<#指令名称> 2)、结束标记:</#指令名称> 3)、空标记:<#指令名称/> 注意: 1) FTL会忽略标记之中的空格,但是,<#和指令 与 </#和指令 之间不能有空格。 2) FTL标记不能够交叉,必须合理嵌套。每个开始标记对应一个结束标记,层层嵌套。 如: <#list> <li> ${数据} <#if 变量> game over! </#if> </#list> 注意事项: 1)、FTL对大小写敏感。所以使用的标记及interpolation要注意大小写。name与NAME就是不同的对象。<#list>是正确的标记,而<#List>则不是。 2)、interpolation只能在文本部分使用,不能位于FTL标记内。如<#if ${var}>是错误的,正确的方法是:<#if var>,而且此处var必须为布尔值。 3)、FTL标记不能位于另一个FTL标记内部,注释例外。注释可以位于标记及interpolation内部。 if, else, elseif 语法 <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 用例 <#if x = 1> x is 1 </#if> <#if x = 1> x is 1 <#else> x is not 1 </#if> We have these animals: <table border=1> <tr><th>Name<th>Price <#list animals as being> <tr> <td> <#if being.size = "large"></#if></#if> ${being.name} <#if being.size = "large"> <td>${being.price} Euros </#list> </table> <#if user = "Big Joe"> It is Big Joe </#if> <#if user != "Big Joe"> It is not Big Joe </#if> switch, case, default, break 语法 <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> <#case refValueN> ... <#break> <#default> ... </#switch> 用例 字符串 <#switch being.size> <#case "small"> This will be processed if it is small <#break> <#case "medium"> This will be processed if it is medium <#break> <#case "large"> This will be processed if it is large <#break> <#default> This will be processed if it is neither </#switch> 数字 <#switch x> <#case x = 1> 1 <#case x = 2> 2 <#default> d </#switch> 如果x=1 输出 1 2, x=2输出 2, x=3 输出d list, break 语法 <#list sequence as item> ... <#if item = "spring"><#break></#if> ... </#list> 关键字 item_index:是list当前值的下标 item_has_next:判断list是否还有值 用例 <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list> 输出 1. winter, 2. spring, 3. summer, 4. autumn include 语法 <#include filename> or <#include filename options> options包含两个属性 encoding=”GBK” 编码格式 parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值的如parse=true,而不是parse=”true” 用例 /common/copyright.ftl包含内容 Copyright 2001-2002 ${me}<br> All rights reserved. 模板文件 <#assign me = "Juila Smith"> <h1>Some test</h1> Yeah. <#include "/common/copyright.ftl" encoding=”GBK”> 输出结果 <h1>Some test</h1> Yeah. <html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> Blah blah... <#include "/copyright_footer.html"> </body> </html> Import 语法 <#import path as hash> 类似于java里的import,它导入文件,然后就可以在当前文件里使用被导入文件里的宏组件 用例 假设mylib.ftl里定义了宏copyright那么我们在其他模板页面里可以这样使用 <#import "/libs/mylib.ftl" as my> <@my.copyright date="1999-2002"/> "my"在freemarker里被称作namespace compress 语法 <#compress> ... </#compress> 用来压缩空白空间和空白的行 用例 <#assign x = " moo \n\n "> (<#compress> 1 2 3 4 5 ${moo} test only I said, test only </#compress>) 输出 (1 2 3 4 5 moo test only I said, test only) escape, noescape 语法 <#escape identifier as expression> ... <#noescape>...</#noescape> ... </#escape> 用例 主要使用在相似的字符串变量输出,比如某一个模块的所有字符串输出都必须是html安全的,这个时候就可以使用该表达式 <#escape x as x?html> First name: ${firstName} <#noescape>Last name: ${lastName}</#noescape> Maiden name: ${maidenName} </#escape> 相同表达式 First name: ${firstName?html} Last name: ${lastName } Maiden name: ${maidenName?html} assign 语法 <#assign name=value> or <#assign name1=value1 name2=value2 ... nameN=valueN> or <#assign same as above... in namespacehash> or <#assign name> capture this </#assign> or <#assign name in namespacehash> capture this </#assign> 用例 生成变量,并且给变量赋值 给seasons赋予序列值 <#assign seasons = ["winter", "spring", "summer", "autumn"]> 给变量test加1 <#assign test = test + 1> 给my namespage 赋予一个变量bgColor,下面可以通过my.bgColor来访问这个变量 <#import "/mylib.ftl" as my> <#assign bgColor="red" in my> 将一段输出的文本作为变量保存在x里 下面的阴影部分输出的文本将被赋值给x <#assign x> <#list 1..3 as n> ${n} <@myMacro /> </#list> </#assign> Number of words: ${x?word_list?size} ${x} <#assign x>Hello ${user}!</#assign> error <#assign x=” Hello ${user}!”> true 同时也支持中文赋值,如: <#assign 语法> java </#assign> ${语法} 打印输出: java global 语法 <#global name=value> or <#global name1=value1 name2=value2 ... nameN=valueN> or <#global name> capture this </#global> 全局赋值语法,利用这个语法给变量赋值,那么这个变量在所有的namespace中是可见的,如果这个变量被当前的assign语法覆盖如<#global x=2> <#assign x=1> 在当前页面里x=2将被隐藏,或者通过${.global.x}来访问[A2] setting 语法 <#setting name=value> 用来设置整个系统的一个环境 locale number_format boolean_format date_format, time_format, datetime_format time_zone classic_compatible 用例 假如当前是匈牙利的设置,然后修改成美国 ${1.2} <#setting locale="en_US"> ${1.2} 输出 1,2 1.2 因为匈牙利是采用“,”作为十进制的分隔符,美国是用“.” C一些常用方法或注意事项 表达式转换类 ${expression}计算expression并输出 #{ expression }数字计算#{ expression ;format}安格式输出数字format为M和m M表示小数点后最多的位数,m表示小数点后最少的位数如#{121.2322;m2M2}输出121.23 数字循环 1..5 表示从1到5,原型number..number 对浮点取整数 ${123.23?int} 输出123 给变量默认值 ${var?default(“hello world<br>”)?html}如果var is null那么将会被hello world<br>替代 判断对象是不是null <#if mouse?exists> Mouse found <#else> 也可以直接${mouse?if_exists})输出布尔形 常用格式化日期 openingTime必须是Date型,详细查看freemarker文档 Reference->build-in referece->build-in for date ${openingTime?date} ${openingTime?date_time} ${openingTime?time} 添加全局共享变量数据模型 在代码里的实现 cfg = Configuration.getDefaultConfiguration(); cfg.setSharedVariable("global", "you good"); 页面实现可以通过global指令,具体查看指令里的global部分 直接调用java对象的方法 ${object.methed(args)} 字符串处理(内置方法) html安全输出 “abc<table>sdfsf”?html 返回安全的html输出,替换掉html代码 xml安全输出 var?xml substring的用法 <#assign user=”hello jeen”> ${user[0]}${user[4]} ${user[1..4]} 输出 : ho ello 类似String.split的用法 “abc;def;ghi”?split(“;”)返回sequence 将字符串按空格转化成sequence,然后取sequence的长度 var?word_list 效果同 var?split(“ ”) var?word_list?size 取得字符串长度 var?length 大写输出字符 var?upper_case 小写输出字符 var?lower_case 首字符大写 var?cap_first 首字符小写 var?uncap_first 去掉字符串前后空格 var?trim 每个单词的首字符大写 var?capitalize 类似String.indexof: “babcdabcd”?index_of(“abc”) 返回1 “babcdabcd”?index_of(“abc”,2) 返回5 类似String.lastIndexOf last_index_of和String.lastIndexOf类似,同上 下面两个可能在代码生成的时候使用(在引号前加”\”) j_string: 在字符串引号前加”\” <#assign beanName = 'The "foo" bean.'> String BEAN_NAME = "${beanName?j_string}"; 打印输出: String BEAN_NAME = "The \"foo\" bean."; js_string: <#assign user = "Big Joe's \"right hand\"."> <script> alert("Welcome ${user}!"); </script> 打印输出: alert("Welcome Big Joe\'s \"right hand\"!"); 替换字符串 replace${s?replace(‘ba’, ‘XY’ )} ${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}将s里的所有的ba替换成xy 规则参数包含:i r m s c f具体含义如下: ·i: 大小写不区分. ·f: 只替换第一个出现被替换字符串的字符串 ·r: XY是正则表达式 ·m: Multi-line mode for regular expressions. In multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string. ·s: Enables dotall mode for regular expressions (same as Perl singe-line mode). In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators. ·c: Permits whitespace and comments in regular expressions. D freemarker在web开发中注意事项 freemarker与webwork整合 web中常用的几个对象 Freemarker的ftl文件中直接使用内部对象: ${Request ["a"]} ${RequestParameters["a"]} ${Session ["a"]} ${Application ["a"]} ${JspTaglibs ["a"]} 与webwork整合之后 通过配置的servlet 已经把request,session等对象置入了数据模型中 在view中存在下面的对象 我们可以在ftl中${req}来打印req对象 req - the current HttpServletRequest res - the current HttpServletResponse stack - the current OgnlValueStack ognl - the OgnlTool instance webwork - an instance of FreemarkerWebWorkUtil action - the current WebWork action exception - optional the Exception instance, if the view is a JSP exception or Servlet exception view view中值的搜索顺序 ${name}将会以下面的顺序查找name值 freemarker variables value stack request attributes session attributes servlet context attributes 在模板里ftl里使用标签 注意,如果标签的属性值是数字,那么必须采用nubmer=123方式给属性赋值 JSP页面 < contentType="text/html;charset=ISO-8859-2" language="java"%> < uri="/WEB-INF/struts-html.tld" prefix="html"%> < uri="/WEB-INF/struts-bean.tld" prefix="bean"%> <html> <body> <h1><bean:message key="welcome.title"/></h1> <html:errors/> <html:form action="/query"> Keyword: <html:text property="keyword"/><br> Exclude: <html:text property="exclude"/><br> <html:submit value="Send"/> </html:form> </body> </html> 模板ftl页面 <#assign html=JspTaglibs["/WEB-INF/struts-html.tld"]> <#assign bean=JspTaglibs["/WEB-INF/struts-bean.tld"]> <html> <body> <h1><@bean.message key="welcome.title"/></h1> <@html.errors/> <@html.form action="/query"> Keyword: <@html.text property="keyword"/><br> Exclude: <@html.text property="exclude"/><br> <@html.submit value="Send"/> </@html.form> </body> </html> 如何初始化共享变量 1. 初始化全局共享数据模型 freemark在web上使用的时候对共享数据的初始化支持的不够,不能在配置初始化的时候实现,而必须通过ftl文件来初始化全局变量。这是不能满主需求的,我们需要在servlet init的时候留出一个接口来初始化系统的共享数据 具体到和webwork整合,因为本身webwork提供了整合servlet,如果要增加全局共享变量,可以通过修改com.opensymphony.webwork.views.freemarker.FreemarkerServlet来实现,我们可以在这个servlet初始化的时候来初始化全局共享变量 与webwork整合配置 配置web.xml <servlet> <servlet-name>freemarker</servlet-name> <servlet-class>com.opensymphony.webwork.views.freemarker.FreemarkerServlet</servlet-class> <init-param> <param-name>TemplatePath</param-name> <param-value>/</param-value> <!—模板载入文件夹,这里相对context root,递归获取该文件夹下的所有模板--> </init-param> <init-param> <param-name>NoCache</param-name> <!—是否对模板缓存--> <param-value>true</param-value> </init-param> <init-param> <param-name>ContentType</param-name> <param-value>text/html</param-value> </init-param> <init-param> <param-name>template_update_delay</param-name> <!—模板更新时间,0表示每次都更新,这个适合开发时候--> <param-value>0</param-value> </init-param> <init-param> <param-name>default_encoding</param-name> <param-value>GBK</param-value> </init-param> <init-param> <param-name>number_format</param-name> <param-value>0.##########</param-value><!—数字显示格式--> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>freemarker</servlet-name> <url-pattern>*.ftl</url-pattern> </servlet-mapping> E高级方法 自定义方法 ${timer("yyyy-MM-dd H:mm:ss", x)} ${timer("yyyy-MM-dd ", x)} 在模板中除了可以通过对象来调用方法外(${object.methed(args)})也可以直接调用java实现的方法,java类必须实现接口TemplateMethodModel的方法exec(List args). 下面以把毫秒的时间转换成按格式输出的时间为例子 public class LongToDate implements TemplateMethodModel { public TemplateModel exec(List args) throws TemplateModelException { SimpleDateFormat mydate = new SimpleDateFormat((String) args.get(0))); return mydate.format(new Date(Long.parseLong((String)args.get(1))); } } 将LongToDate对象放入到数据模型中 root.put("timer", new IndexOfMethod()); ftl模板里使用 <#assign x = "123112455445"> ${timer("yyyy-MM-dd H:mm:ss", x)} ${timer("yyyy-MM-dd ", x)} 输出 2001-10-12 5:21:12 2001-10-12 自定义 Transforms 实现自定义的<@transform>文本或表达式</@transform>的功能,允许对中间的最终文本进行解析转换 例子:实现<@upcase>str</@upcase> 将str转换成STR 的功能 代码如下: import java.io.*; import java.util.*; import freemarker.template.TemplateTransformModel; class UpperCaseTransform implements TemplateTransformModel { public Writer getWriter(Writer out, Map args) { return new UpperCaseWriter(out); } private class UpperCaseWriter extends Writer { private Writer out; UpperCaseWriter (Writer out) { this.out = out; } public void write(char[] cbuf, int off, int len) throws IOException { out.write(new String(cbuf, off, len).toUpperCase()); } public void flush() throws IOException { out.flush(); } public void close() { } } } 然后将此对象put到数据模型中 root.put("upcase", new UpperCaseTransform()); 在view(ftl)页面中可以如下方式使用 <@upcase> hello world </@upcase> 打印输出: HELLO WORLD F.Built-ins ${x?upper_case} – 小写变大写 ${test?html} - 转换为HTML编码格式 ${repeat("A", B)} – 复制B次A Example: ${test?html} ${test?upper_case?html} Assuming that test stores the string ``Tom & Jerry'', the output will be: Tom & Jerry TOM & JERRY --------- ${repeat("What", 3)} will print: :WhatWhatWhat 1. String内置的JavaScript转换: js_string 用途:用于JavaScript转义,转换',",换行等特殊字符 模板: <script> alert("${errorMessage?js_string}"); </script> 输出: <script> alert("Readonly\'s pet name is \"Cross Bone\""); </script> 2.内置的默认值处理:default 用途: 用于处理默认值 模本: User: ${userLogin.name?default("Anonymous")} <td>${(employee.department.manager.name)?default(" ")}</td> 输出: User: Anonymous <td> </td> 注,可以对整个对象树加上(),再用内置处理器这种方便的做法,偶也是最近刚学会的,以前一直用很傻的方法做..... 3. Sequence内置的计数器: xxx_index 用途:显示序号 模板: <#list employees as e> ${e_index}. ${e.name} </#list> 输出: 1. Readonly 2. Robbin 4. Sequence内置的分段器: chunk 用途:某些比较BT的排版需求 模板: <#assign seq = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']> <#list seq?chunk(4) as row> <ul> <li><#list row as cell>${cell} </#list> </#list> <#list seq?chunk(4, '-') as row> <tr> <td><#list row as cell>${cell} </#list></td> </tr> </#list> 输出: <ul> <li>a <li>b <li>c <li>d <ul> <li>e <li>f <li>g <li>h <ul> <li>i <li>j <tr> <td>a</td> <td>b</td> <td>c</td> <td>d</td> </tr> <tr> <td>e</td> <td>f</td> <td>g</td> <td>h</td> </tr> <tr> <td>i</td> <td>j</td> <td>-</td> <td>-</td> </tr> String ${"It's \"quoted\" and this is a backslash: \\"} ${'It\'s "quoted" and this is a backslash: } ${r"${foo}"} raw字符串,原封不动地现实引号中的内容 ps:前一种是用双引号来引用字符串,后一种是用单引号来引用字符串。 分别需要对双引号和单引号进行转义 ${"${user}${user}${user}${user}"} ${user + user + user + user} 效果相同 ★substring ${user[0]}${user[4]} ${user[1..4]} ${user[4..]} ★number 不支持科学计数法 小数点前面的零不能省略 ★sequences <#list ["winter", "spring", "summer", "autumn"] as x> ${x} </#list> <#list 2..5 as x> ${x} </#list> <#list [2,3,4,5] as x> ${x} </#list> 数组的拼接 <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user> - ${user} </#list> ★hash <#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}> - Joe is ${ages.Joe} - Fred is ${ages.Fred} - Julia is ${ages.Julia} 注意重复的键对应的值取最后的一个 ★运算 ${5/2?int} 显示2 cap_first : 首字母大写 capitalize: 所有单词首刺目大写 html : 转换为HTML格式 < replaced with < > replaced with > & replaced with & " replaced with " index_of : 显示元素所在的位置 "abcabc"?index_of("bc") 返回值为1(下标从0开始) Contains:判断是否存在字符 <#if "piceous"?contains("ice")>It contains "ice"</#if> 输出: It contains "ice" Replace :替换 split(“XX”):截取XX之后的字符 <#list "someMOOtestMOOtext"?split("MOO") as x> - ${x} </#list> 输出: - some - test - text starts_with :字符串由什么开始返回布尔型 trim :去掉空格 seq_index_of 数组中元素的位置 <#assign colors = ["red", "green", "blue"]> ${colors?seq_index_of("blue")} 输出: 2 Default : 设置变量的默认值 Exists:放在if句 如果没有….. <#if mouse?exists> Mouse found <#else> No mouse found </#if> Creating mouse... <#assign mouse = "Jerry"> <#if mouse?exists> Mouse found <#else> No mouse found </#if> 输出 : No mouse found Creating mouse... Mouse found if_exists 放在一般语句 (${mouse?if_exists}) Creating mouse... <#assign mouse = "Jerry"> (${mouse?if_exists}) 输出: () Creating mouse... (Jerry) 删除空白行和空格 <#compress> ... </#compress> 让此标记内的代码都执行<#escape 后的?参数 <#escape> </#escape> <#escape x as x?html> From: ${mailMessage.From} Subject: ${mailMessage.Subject} <#noescape>Message: ${mailMessage.htmlFormattedBody}</#noescape> ... </#escape> 输出: From: ${mailMessage.From?html} Subject: ${mailMessage.Subject?html} Message: ${mailMessage.htmlFormattedBody} ... [A1]默认值 [A2]<#import “lib/abc.ftl” as abc>这里的abc叫做namespace chunk, is_date, last, root, j_string, contains, is_hash, long, float, ends_with, namespace, matches, time, values, seq_last_index_of, uncap_first, byte, substring, is_transform, web_safe, groups, seq_contains, is_macro, index_of, word_list, int, is_method, eval, parent, xml, number, capitalize, if_exists, rtf, node_type, double, is_directive, url, size, default, is_boolean, split, node_name, is_enumerable, seq_index_of, is_sequence, sort, is_node, sort_by, left_pad, cap_first, interpret, children, node_namespace, chop_linebreak, date, short, last_index_of, is_collection, ancestors, length, trim, datetime, is_string, reverse, c, keys, upper_case, js_string, has_content, right_pad, replace, is_hash_ex, new, is_number, is_indexable, lower_case, string, exists, html, first, starts_with ##############2222222222222222############### struts2.0 标签+ftl标签 FreeMarker中文API手册(完整) http://blog.csdn.net/junjun16818/article/details/6990068 三目: ${true?string('5','7')} ${line.class.simpleName} <#if line.class.simpleName=="ViewLine">你好</#if> list里面是object数组 <#if (areaList?exists)> <#list areaList as line> <span style="background-color:#${(sc[(line_index)%6])}">${line[1]}:${line[0]}</span> </#list> </#if> 取得list的长度: <#if (pageInfo.resultList?size>0)> 截取字符串:<#if news.title?length gt 14>${news.title.substring(0,14)}...<#else>${news.title?if_exists}</#if> 拆分字符数组 <#if (lineInfo.lineDate?exists)&&(lineInfo.lineDate?length>10)> <#list lineInfo.lineDate?split(",") as d> <input type="text" name="lineInfo.lineDate" id="lineDate" value="${d}" onclick="WdatePicker({dateFmt:'yyyy-MM-dd', skin:'whyGreen'})"/> </#list> </#if> 1.注释: 包含在<#--和--> 2.注意: 由于Freemarker会将>解释成FTL标记的结束字符,所以对于>和>=可以使用括号来避免这种情况,例如 <#if (x > y)> 3.<#local y = "test"> 定义局部变量 4.<#import "/lib/my_test.ftl" as my> 导入模板文件 指定名字空间 my 5. if指令 <#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#else> Pythons are not cheaper than elephants today. </#if> 6. list指令以及列表序号 <#list animals as being> 第${being_index+1}个<#--默认是0开始--> <tr><td>${being.name}<td>${being.price} Euros </#list> <#list ["winter", "spring", "summer", "autumn"] as x> ${x} </#list> <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user> - ${user} </#list> 输出结果是: - Joe - Fred - Julia - Kate include指令 <#include "/copyright_footer.html"> 7.判断是否为空 ${userInfo.userName?if_exists} <#if ((user.sex)!'')=='1'>男<#elseif ((user.sex)!'')=='2'>女</#if> <#if searchType ? exists && searchType=='on'>checked</#if> <#if time ? exists && (time!'')=='y' || (time!'')=='m' || (time!'')=='d'>统计条件<#else>保证金返款数量</#if> <#if ((time)!'')=='y'>按年统计<#elseif ((time)!'')=='m'>按月统计<#elseif ((time)!'')=='d'>按日统计<#else>默认按日统计</#if> 8.截取字符串 ${carInfo.carNum.substring(0,1)} 9.freemarker的replace功能 替换字符串 replace 线路标签:${lineInfo.lineLableDescribe?replace('#','、')} ${s?replace(‘ba’, ‘XY’ )} ${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}将s里的所有的ba替换成xy 规则参数包含: i r m s c f 具体含义如下: · i: 大小写不区分. · f: 只替换第一个出现被替换字符串的字符串 · r: XY是正则表达式 · m: Multi-line mode for regular expressions. In multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string. · s: Enables dotall mode for regular expressions (same as Perl singe-line mode). In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators. · c: Permits whitespace and comments in regular expressions. 10.三目运算 ${true?string('5','7')} 11.string格式化单个Interpolation,下面是一个例子: <#setting number_format="currency"/> <#assign answer=42/> ${answer} ${answer?string} <#-- the same as ${answer} --> ${answer?string.number} ${answer?string.currency} ${answer?string.percent} 输出结果是: $42.00 $42.00 42 $42.00 4,200% 12.插入日期值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个使用格式模式的例子: ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")} ${lastUpdated?string("EEE, MMM d, ''yy")} ${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")} 输出的结果类似下面的格式: 2003-04-08 21:24:44 Pacific Daylight Time Tue, Apr 8, '03 Tuesday, April 08, 2003, 09:24:44 PM (PDT) 13.插入布尔值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个例子: <#assign foo=true/> ${foo?string("yes", "no")} 输出结果是: yes <#if cList?exists> <#assign index = 1 /> <#list cList as cList> <#if index==1 || index %3==0> <div class="base_row"> </#if> <div class="fldivlr5"><font class="font_gray">车型:</font></div> <div class="fldivlr5">三厢轿车</div> <#if index %3==0 || !cList_has_next> </div> </#if> <#assign index=index+1 /> </#list> </#if> Freemarker 内置函数 数字、字符串、日期格式化 一、 Sequence的内置函数 1. sequence?first 返回sequence的第一个值。 2. sequence?last 返回sequence的最后一个值。 3. sequence?reverse 将sequence的现有顺序反转,即倒序排序 4. sequence?size 返回sequence的大小 5. sequence?sort 将sequence中的对象转化为字符串后顺序排序 6. sequence?sort_by(value) 按sequence中对象的属性value进行排序 二、 Hash的内置函数 1. hash?keys 返回hash里的所有key,返回结果为sequence 2. hash?values 返回hash里的所有value,返回结果为sequence 例如: <#assign user={“name”:“hailang”, “sex”:“man”}> <#assign keys=user?keys> <#list keys as key> ${key}=${user[key]} </#list> 三、 操作字符串函数 1. substring(start,end)从一个字符串中截取子串 start:截取子串开始的索引,start必须大于等于0,小于等于end end: 截取子串的长度,end必须大于等于0,小于等于字符串长度,如果省略该参数,默认为字符串长度。 例子: ${‘str’?substring(0)}à结果为str ${‘str’?substring(1)}à结果为tr ${‘str’?substring(2)}à结果为r ${‘str’?substring(3)}à结果为 ${‘str’?substring(0,0)}à结果为 ${‘str’?substring(0,1)}à结果为s ${‘str’?substring(0,2)}à结果为st ${‘str’?substring(0,3)}à结果为str 2. cap_first 将字符串中的第一个单词的首字母变为大写。 ${‘str’?cap_first}à结果为Str 3. uncap_first将字符串中的第一个单词的首字母变为小写。 ${‘Str’?cap_first}à结果为str 4. capitalize将字符串中的所有单词的首字母变为大写 ${‘str’? capitalize}à结果为STR 5. date,time,datetime将字符串转换为日期 例如: <#assign date1=”2009-10-12”?date(“yyyy-MM-dd”)> <#assign date2=”9:28:20”?time(“HH:mm:ss”)> <#assign date3=” 2009-10-12 9:28:20”?time(“HH:mm:ss”)> ${date1}à结果为2009-10-12 ${date2}à结果为9:28:20 ${date3}à结果为2009-10-12 9:28:20 注意:如果指定的字符串格式不正确将引发错误。 6. ends_with 判断某个字符串是否由某个子串结尾,返回布尔值。 ${“string”?ends_with(“ing”)?string} 返回结果为true 注意:布尔值必须转换为字符串才能输出 7. html 用于将字符串中的<、>、&和“替换为对应得<>":& 8. index_of(substring,start)在字符串中查找某个子串,返回找到子串的第一个字符的索引,如果没有找到子串,则返回-1。 Start参数用于指定从字符串的那个索引处开始搜索,start为数字值。 如果start大于字符串长度,则start取值等于字符串长度,如果start小于0, 则start取值为0。 ${“string”?index_of(“in”) à结果为3 ${“string”?index_of(“ab”) à结果为-1 9.length返回字符串的长度 ${“string”?length}à结果为6 10. lower_case将字符串转为小写 ${“STRING”?lower_case}à结果为string 11.upper_case将字符串转为大写 ${“string”?upper_case}à结果为STRING 12. contains 判断字符中是否包含某个子串。返回布尔值 ${“string”?contains(“ing”)?string} à结果为true 注意:布尔值必须转换为字符串才能输出 13. number将字符串转换为数字 ${“111.11”?number}à结果为111.11 14.replace用于将字符串中的一部分从左到右替换为另外的字符串。 ${“strabg”?replace(“ab”,”in”)} à结果为string 15.split使用指定的分隔符将一个字符串拆分为一组字符串 <#list “This|is|split”?split(“|”) as s> ${s} </#list> 结果为: This is split 16. trim 删除字符串首尾空格 ${“ String ”?trim} à结果为String 四、 操作数字 1. c 用于将数字转换为字符串 ${123?c} à结果为123 2. string用于将数字转换为字符串 Freemarker中预订义了三种数字格式:number,currency(货币)和percent(百分比)其中number为默认的数字格式转换 例如: <#assign tempNum=20> ${tempNum} ${tempNum?string.number}或${tempNum?string(“number”)} à结果为20 ${tempNum?string.currency}或${tempNum?string(“currency”)} à结果为¥20.00 ${tempNum?string. percent}或${tempNum?string(“percent”)} à结果为2,000% 五、 操作布尔值 string 用于将布尔值转换为字符串输出 true转为“true”,false转换为“false” foo?string(“yes”,”no”)如果布尔值是true,那么返回“yes”,否则返回no <#assign index = 1 /> <#list pageInfo.resultList as p> <tr class=<#if index%2==0>"sealistra"<#else>"sealistrb"</#if> align="center"> <td align="center">${index}</td> ${p.userName?if_exists} <td><#if ((p.roleType)!'')=='1'>司机<#elseif ((p.roleType)!'')=='2'>乘客</#if></td> <td><#if ((p.journeyType)!'')=='1'>单程<#elseif ((p.journeyType)!'')=='2'>往返</#if></td> <td>${(p.ver)!""}</td> <td> <#if ((p.statusFlag)!'')=='0'>默认 <#elseif ((p.statusFlag)!'')=='1'>匹配成功 </#if> </td> <td> <#if p.createTime?exists >${p.createTime?string("yyyy-MM-dd HH:mm:ss")}</#if> </td> </tr> <#assign index=index+1 /> </#list> if, else, elseif 语法: <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 备注:condition、condition2···必须为boolean 类型,<#elseif ··>、<#else>可有0或多个。 实例: <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 <#elseif x > 4> x is 4 <#else> x is not 1 nor 2 nor 3 nor 4 </#if> 备注:< 或 > 号 必须转义,否则出错。。转义请参考其他文档。 switch, case, default, break 语法 <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> ... <#case refValueN> ... <#break> <#default> ... </#switch> 备注:该指令官方不推荐使用了,可以用if, else, elseif 指令代替。 list, break 语法 <#list sequence as item> ... </#list> 备注: sequence 为一个sequence 或者 collection 类型。item 为 循环的变量。该指令中包含有两个特殊的循环变量, item_index:该值为当前循环的值。 item_has_next:该值为一个boolean类型,表明该循环是否含有下一个(是否为循环到了最后一个) 实例: <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list> 输出: 1. winter, 2. spring, 3. summer, 4. autumn 实例: <#assign x=3> <#list 1..x as i> ${i} </#list> 备注:当x 为一个数值序列时,可以使用该list 列出两个数值之间的值。(适合于表格的序号填写) 实例: <#list seq as x> ${x} <#if x = "spring"><#break></#if> </#list> 备注:可以用<#if···><#break> 来终止该循环。 freemarker常见语法大全 FreeMarker的插值有如下两种类型:1,通用插值${expr};2,数字格式化插值:#{expr}或#{expr;format} ${book.name?if_exists } //用于判断如果存在,就输出这个值 ${book.name?default(‘xxx’)}//默认值xxx ${book.name!"xxx"}//默认值xxx ${book.date?string('yyyy-MM-dd')} //日期格式 ${book?string.number} 20 //三种不同的数字格式 ${book?string.currency}--<#-- $20.00 --> ${book?string.percent}—<#-- 20% --> <#assign foo=ture /> //声明变量,插入布尔值进行显示 ${foo?string("yes","no")} <#-- yes --> <等大小比较符号使用需要注意:(xml的原因),可以用于比较数字和日期 使用lt、lte、gt和gte来替代<、<=、>和>= 也可以使用括号<#if (x>y)> 内置函数: 调用区别于属性的访问,使用?代替. 常见的一些内置函数 对于字符串 html-对字符串进行HTML编码 cap_first-使字符串第一个字母大写 lower_case-将字符串转换成小写 trim-去掉字符串前后的空白字符 对于Sequences(序列) size-获得序列中元素的数目 对于数字 int-取得数字的整数部分(如-1.9?int的结果是-1) 对于集合,可以使用数组的方式,使用下标索引进行访问 逻辑判断: if................ <#if condition>... <#elseif condition2>... <#elseif condition3>...... <#else>... Boolean类型的空值判断 空值判断可以写成<#if book.name?? > //注意${}为变量的渲染显示,而<>为定义等操作符的定义 switch............ <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> ... <#case refValueN> ... <#break> <#default> ... </#switch> 快速定义int区间的集合 <#assign l=0..100/> //注意不需要[] 3:循环读取集合: 注意/的使用 <#list student as stu> ${stu}<br/> </#list> 与jstl循环类似,也可以访问循环的状态 item_index:当前变量的索引值 item_has_next:是否存在下一个对象 其中item名称为as后的变量名,如stu 集合长度判断 <#if student?size != 0></#if> 判断=的时候,注意只要一个=符号,而不是== 宏/模板 初步了解: 使用更像一个闭包closure,可以定义后,在脚本中任意地方引用,并原地起作用 <#macro greet> <font size="+2">Hello Joe!</font> </#macro> 使用的方式为: <@greet></@greet> //同xml可以简写成<@greet/> 宏的参数定义,类似js,在宏名后 带参数进行传递定义 <#macro greet person color> ${person} </#macro> 调用带参数时,注意使用类似XML的属性格式进行传递,不需要关心顺序问题 <@greet person="Fred" color="black"/> 参数默认值定义,如果没有,就必须要求传递完整的参数列表 <#macro greet person color="black"> <font size="+2" color="${color}">Hello ${person}!</font> </#macro> 使用xml的嵌套内容进行传递宏调用,关键标签 <#nested> <#macro border> <table border=4 cellspacing=0 cellpadding=4><tr><td> <#nested> </tr></td></table> </#macro> 调用时: <@border>The bordered text</@border> <#nested> 标签可以在宏中多次调用,也可以将多个宏组合进行嵌套 for循环的精简版: <#list 1..count as x> </#list> 宏的循环变量,配合嵌套标签进行参数传递, <#macro repeat count> <#list 1..count as x> <#nested x, x/2, x==count> //这里的三个参数,将会传递到嵌套内容中 </#list> </#macro> <@repeat count=4 ; c, halfc, last> ${c}. ${halfc}<#if last> Last!</#if> //这里的内容由macro中的<#nested>进行参数的传递,传递的数量任意,当注意需要宏接受这些 </@repeat> 上述还需要注意;的使用 参数的数量是可变的,并不要求全部都有,但是效果不同 在模板中定义变量 在模板中定义的变量有三种类型: plain变量:可以在模板的任何地方访问,包括使用include指令插入的模板,使用assign指令创建和替换。 局部变量:在宏定义体中有效,使用local指令创建和替换。 循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建;宏的参数是局部变量,而不是循环变量 <#assign x = "plain"> //全局的plain变量 内部循环变量将会隐藏同名的外部循环变量 外部导入的使用,可以用于模块化,并且提供公用性 如:lib/my_lib.ftl文件 <#macro copyright date> <p>Copyright (C) ${date} Julia Smith. All rights reserved. <br>Email: ${mail}</p> </#macro> <#assign mail = "jsmith@acme.com"> lib/my_inc.ftl文件 <#import "/lib/my_test.ftl" as my> <#assign mail="fred@acme.com"> <@my.copyright date="1999-2002"/> ${my.mail} ${mail} 输出结果将不会出现冲突 对于库中的变量修改,使用in关键字 <#assign mail="jsmith@other.com" in my> 函数定义:区别于宏对象,带返回值 <#function name param1 param2><#return val></#function>函数,有返回参数 stringA[M .. N] 取子字符串,类似substring(stringA, M, N) <#include "/copyright_footer.html"> 导入其他页面元素 <#include filename options> options包含两个属性 encoding=”GBK” 编码格式 parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值的如parse=true,而不是 parse=”true” hash与list的定义 <#assign c= {"a":"orz","b":"czs"}> ${c.a} List片段可以采用: products[10..19] or products[5..] 的格式进行定义,当只局限于数字 <#assign c= [1,2,3,4,5,6,6,7]> <#list c[1..3] as v> ${v} </#list> 对变量的缺省处理 product.color!"red" 用compress directive或者transform来处理输出。 <#compress>...</#compress>:消除空白行。 <@compress single_line=true>...</@compress>将输出压缩为一行。都需要包裹所需文档 freemarker可用"["代替"<".在模板的文件开头加上[#ftl]. 数字输出的另外一种方式 #{c.a;m0} 区别于${},这个例子是用于输出数字的格式化,保留小数的位数,详细如下 数字格式化插值可采用#{expr;format}形式来格式化数字,其中format可以是: mX:小数部分最小X位 MX:小数部分最大X位 在定义字符串的时候,可以使用''或者"",对特殊字符,需要使用\进行转义 如果存在大量特殊字符,可以使用${r"..."}进行过滤 ${r"${foo}"} ${r"C:\foo\bar"} Map对象的key和value都是表达式,但是key必须是字符串 可以混合使用.和[""]访问 book.author["name"] //混合使用点语法和方括号语法 为了处理缺失变量,FreeMarker提供了两个运算符: 用于防止对象不存在而导致的异常 !:指定缺失变量的默认值 ??:判断某个变量是否存在,返回boolean值 noparse指令指定FreeMarker不处理该指定里包含的内容,该指令的语法格式如下: <#noparse>...</#noparse> ${firstName?html} 使用html对字符进行格式化处理,对于<等的过滤 escape , noescape指令,对body内的内容实用统一的表达式 看如下的代码: <#escape x as x?html> First name:${firstName} Last name:${lastName} Maiden name:${maidenName} </#escape> 上面的代码等同于: First name:${firstName?html} Last name:${lastName?html} Maiden name:${maidenName?html} 定义全局变量的方式 <#assign name1=value1 name2=value2 / > // 可以同时定义多个变量,也可以使用循环来给变量赋值 <#assign x> <#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as n> ${n} </#list> </#assign> ${x} setting指令,用于动态设置freeMarker的运行环境: 该指令用于设置FreeMarker的运行环境,该指令的语法格式如下:<#setting name=value>,在这个格式中,name的取值范围包含如下几个: locale:该选项指定该模板所用的国家/语言选项 number_format:指定格式化输出数字的格式 boolean_format:指定两个布尔值的语法格式,默认值是true,false date_format,time_format,datetime_format:指定格式化输出日期的格式 time_zone:设置格式化输出日期时

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值