在线一区二区三区精品,亚洲精品乱码久久久久久,天堂а在线中文在线无限看推荐 http://www.aygfsteel.com/libin2722/category/34664.html虛其心,可解天下之問;專其心,可治天下之學(xué);靜其心,可悟天下之理;恒其心,可成天下之業(yè)。zh-cnFri, 13 Aug 2010 06:55:10 GMTFri, 13 Aug 2010 06:55:10 GMT60Freemarker中使用OSCachehttp://www.aygfsteel.com/libin2722/articles/328205.html禮物禮物Sat, 07 Aug 2010 07:53:00 GMThttp://www.aygfsteel.com/libin2722/articles/328205.htmlhttp://www.aygfsteel.com/libin2722/comments/328205.htmlhttp://www.aygfsteel.com/libin2722/articles/328205.html#Feedback0http://www.aygfsteel.com/libin2722/comments/commentRss/328205.htmlhttp://www.aygfsteel.com/libin2722/services/trackbacks/328205.html
例如:
<#assign oscache=JspTaglibs['http://www.opensymphony.com/oscache']/>

<#assign fowUrlaa="">
<#if RequestParameters.fowUrl?exists>
<#assign fowUrlaa="${RequestParameters.fowUrl}">
</#if>
<@oscache.cache key="__oscache_categories" time=300>
??? ${fowUrlaa}
</@oscache.cache>

然后再URL上添加參數(shù)測(cè)試:?fowUrl=12fas11

禮物 2010-08-07 15:53 發(fā)表評(píng)論
]]>
FreeMarker設(shè)計(jì)指南http://www.aygfsteel.com/libin2722/articles/252665.html禮物禮物Wed, 28 Jan 2009 15:20:00 GMThttp://www.aygfsteel.com/libin2722/articles/252665.htmlhttp://www.aygfsteel.com/libin2722/comments/252665.htmlhttp://www.aygfsteel.com/libin2722/articles/252665.html#Feedback0http://www.aygfsteel.com/libin2722/comments/commentRss/252665.htmlhttp://www.aygfsteel.com/libin2722/services/trackbacks/252665.html閱讀全文

禮物 2009-01-28 23:20 發(fā)表評(píng)論
]]>
用freemarker生產(chǎn)靜態(tài)頁面http://www.aygfsteel.com/libin2722/articles/252664.html禮物禮物Wed, 28 Jan 2009 15:17:00 GMThttp://www.aygfsteel.com/libin2722/articles/252664.htmlhttp://www.aygfsteel.com/libin2722/comments/252664.htmlhttp://www.aygfsteel.com/libin2722/articles/252664.html#Feedback0http://www.aygfsteel.com/libin2722/comments/commentRss/252664.htmlhttp://www.aygfsteel.com/libin2722/services/trackbacks/252664.html

FreeMarker概述

  • FreeMarker是一個(gè)模板引擎,一個(gè)基于模板生成文本輸出的通用工具,使用純Java編寫
  • Template + data model = output
  • Hello world

  • FreeMarkerTest.java
 
import java.io.StringWriter;import java.util.HashMap;import java.util.Locale;
 
import freemarker.template.Configuration;import freemarker.template.Template;
 
publicclass FreeMarkerTest {
 
publicstaticvoid main(String[] args){
FreeMarkerTest test = new FreeMarkerTest();
test.sayHello("Hermit");
}
 
publicvoid sayHello(String name){
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(), "/");
 
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
Template template;
Locale.setDefault(Locale.ENGLISH);
try{
template = freemarkerCfg.getTemplate("Hello.ftl");
template.setEncoding("UTF-8");
HashMap root = newHashMap();
root.put("user", name);
 
StringWriter writer = newStringWriter();
template.process(root, writer);
System.out.println(writer.toString());
}catch(Exception e){
e.printStackTrace();
}}
 
 
 
}
 
  • Hello.ftl
 
 
Hello ${user}!
 
 
  • 輸出

Hello Hermit!


空值的處理

在我們的程序中難免會(huì)碰到值為空的時(shí)候,如果用一個(gè)空值直接去替換模板中的標(biāo)記,freemarker會(huì)毫不猶豫的拋出異常,并把錯(cuò)誤信息直接寫到輸出結(jié)果里。為了對(duì)付這種情況我們有兩種寫法

  • 模板
 
Hello ${user!}!
Hello ${user?if_exists}
Hello ${user!'your name'}!
Hello ${user?default('your name')}
 
  • 程序
 
test.sayHello(null);
 
  • 輸出
 
Hello !
Hello your name!
Hello
Hello your name
 

freemarker國際化模板

freemarker支持多語言國際化,只要把模板名稱按照java資源文件的寫法就可以了,也就是name_語言_國家地區(qū).ftl 如果找不到對(duì)應(yīng)的語言,就會(huì)用默認(rèn)語言的模板。

  • 程序
 
import java.io.StringWriter;import java.util.HashMap;import java.util.Locale;
 
import freemarker.template.Configuration;import freemarker.template.Template;
 
publicclass FreeMarkerTest {
 
publicstaticvoid main(String[] args){
FreeMarkerTest test = new FreeMarkerTest();
test.sayHello("hermit",Locale.CHINA);
test.sayHello("hermit",Locale.ENGLISH);
}
 
publicvoid sayHello(String name,Locale locale){
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(), "/");
 
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
Template template;
Locale.setDefault(Locale.ENGLISH);
try{
template = freemarkerCfg.getTemplate("Hello.ftl",locale);
template.setEncoding("UTF-8");
HashMap root = newHashMap();
root.put("user", name);
 
StringWriter writer = newStringWriter();
template.process(root, writer);
System.out.println(writer.toString());
}catch(Exception e){
e.printStackTrace();
}
}

  
}
 
  • 默認(rèn)語言模版:Hello.ftl
Hello ${user!}! 
中文模版:Hello_zh_CN.ftl
你好 ${user!}!

輸出
你好 hermit!
Hello hermit!
 

在struts項(xiàng)目中使用freemarker

1、引入freemarker.jar
2、web.xml加入
	<!-- FreeMarker view servlet (to replace JSP) -->
<servlet>
<servlet-name>freemarker</servlet-name><servlet-class>
freemarker.ext.servlet.FreemarkerServlet
</servlet-class>
 
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>
/</param-value>
</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>

 
<!-- FreeMarker settings: --><init-param><param-name>template_update_delay</param-name><param-value>0</param-value>
<!-- 0 is for development only! Use higher value otherwise. -->

</init-param>
<init-param><param-name>default_encoding</param-name>
<param-value>
utf-8</param-value></init-param>
<init-param><param-name>locale</param-name><param-value>en_US</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>
 
3、一個(gè)示例頁面
 
<html><head><title>Say Hello</title><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=utf-8"></head><body><h1>Hello ${user}!</h1></body></html>
 

我們完全可以用freemarker的模板取代JSP頁面。用freemarker的模板看起更簡(jiǎn)潔,可讀性更強(qiáng)。比如現(xiàn)在struts2的UI標(biāo)簽就是用freemarker做的。

freemarker用struts標(biāo)簽做國際化

  • 示例模板
<#assign  html =JspTaglibs["/WEB-INF/struts-html.tld"]><#assign  bean =JspTaglibs["/WEB-INF/struts-bean.tld"]><#assign  logic =JspTaglibs["/WEB-INF/struts-logic.tld"]><html><head><title> FreeMarker Struts Example </title><metahttp-equiv ="Content-type"content ="text/html; charset=utf-8"></ head ><body><@bean.message key ="hello"  arg0 ="hermit"/></body></html> 

主要是引入標(biāo)簽的時(shí)候要這樣寫:

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

freemarker直接使用資源文件進(jìn)行多語言國際化

  • 程序
import java.io.StringWriter;import java.util.HashMap;import java.util.Locale;import java.util.ResourceBundle;
 
import freemarker.ext.beans.BeansWrapper;import freemarker.ext.beans.ResourceBundleModel;import freemarker.template.Configuration;import freemarker.template.Template;
 
publicclass FreeMarkerTest {
 
publicstaticvoid main(String[] args){
FreeMarkerTest test = new FreeMarkerTest();
test.sayHello("hermit",Locale.CHINA);
test.sayHello("hermit",Locale.ENGLISH);
}
 
publicvoid sayHello(String name,Locale locale){
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(), "/");
 
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
Template template;
Locale.setDefault(Locale.ENGLISH);
try{
template = freemarkerCfg.getTemplate("Hello.ftl");
template.setEncoding("UTF-8");
HashMap root = newHashMap();
root.put("user", name);
ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("ApplicationResources",locale);
ResourceBundleModel rsbm = new ResourceBundleModel(RESOURCE_BUNDLE,new BeansWrapper());
root.put("bundle", rsbm);
StringWriter writer = newStringWriter();
template.process(root, writer);
System.out.println(writer.toString());
}catch(Exception e){
e.printStackTrace();
}}
 
 
 
}

模板
${bundle("hello","hermit")} 

默認(rèn)語言資源文件
hello=Hello {0}\! 

中文資源文件

hello=你好 {0}\!
  • 輸出
你好 hermit!
Hello hermit!

關(guān)鍵的地方就是用ResourceBundleModel把ResourceBundle轉(zhuǎn)換一下。

常用的2種加載模板的方式

  • 普通java類根據(jù)當(dāng)前class上下文環(huán)境加載模板
cfg.setClassForTemplateLoading(this.getClass(), "/");
  • 在web項(xiàng)目中根據(jù)servlet上下文環(huán)境加載模板
cfg.setServletContextForTemplateLoading(this.getServlet().getServletContext(), "/");


禮物 2009-01-28 23:17 發(fā)表評(píng)論
]]>
我的第一個(gè)FreeMarker程序http://www.aygfsteel.com/libin2722/articles/229284.html禮物禮物Tue, 16 Sep 2008 16:00:00 GMThttp://www.aygfsteel.com/libin2722/articles/229284.htmlhttp://www.aygfsteel.com/libin2722/comments/229284.htmlhttp://www.aygfsteel.com/libin2722/articles/229284.html#Feedback0http://www.aygfsteel.com/libin2722/comments/commentRss/229284.htmlhttp://www.aygfsteel.com/libin2722/services/trackbacks/229284.html1、java應(yīng)用程序中
    我用maven導(dǎo)入FreeMarker的jar包
   
    <dependency>
      <groupId>freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.8</version>
    </dependency>

    package com.test;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Test {

    /** *//**
     * @param args
     */
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        configuration.setTemplateLoader(new ClassTemplateLoader(Test.class, "/com/test"));
        try {
            Template template = configuration.getTemplate("temp.ftl");
            StringWriter writer = new StringWriter();
            Map<String, Object> context = new HashMap<String, Object>();
           
            context.put("message", "我的第一個(gè)FreeMarker程序");
           
            template.process(context, writer);
            System.out.println(writer.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

這里是用java應(yīng)用程序,需要加入下面兩句(設(shè)置模板文件載入):
方法一:
  configuration.setObjectWrapper(new DefaultObjectWrapper());
  configuration.setTemplateLoader(new ClassTemplateLoader(Test.class, "/com/test"));

其中"/com/test" 是模板文件所在的文件夾,前面的“/”必須,這里我的模板文件和當(dāng)前java類在同一路徑下,則這樣寫,如果你的模板文件在src跟目錄下,這里只需要寫“/”就可以了

context.put("message", "我的第一個(gè)FreeMarker程序");
是模板文件中用到的變量,map中的變量可以是javabean,也可以是對(duì)象


方法二:
configuration.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
這里主要針對(duì)Servlet的時(shí)候,當(dāng)然在Servlet中也可以用方法一提到的寫法
package com.newegg.lab.freemarker.servlet;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/** *//**
 * Servlet implementation class for Servlet: FreemarkerServlet
 *
 */
public class FreemarkerServlet extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {

    private Configuration configuration;

    private Template template;
    /**//*
     * (non-Java-doc)
     *
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public FreemarkerServlet() {
        super();
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        configuration = null;
    }

    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        configuration = new Configuration();
        configuration.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
//        configuration.setObjectWrapper(new DefaultObjectWrapper());
//        configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerServlet.class, "/"));
    }

    /**//*
     * (non-Java-doc)
     *
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }

    /**//*
     * (non-Java-doc)
     *
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Map root = new HashMap();
        root.put("message", "Hello World!的的的的");

        // Get the templat object
        Template t = configuration.getTemplate("test.ftl");

        // Prepare the HTTP response:
        // - Use the charset of template for the output
        // - Use text/html MIME-type
        response.setContentType("text/html; charset=" + t.getEncoding());
        Writer out = response.getWriter();

        // Merge the data-model and the template
        try {
            t.process(root, out);

            StringWriter stringWriter = new StringWriter();
            t.process(root, stringWriter);
            System.out.println(stringWriter.toString());
        } catch (TemplateException e) {
            throw new ServletException(
                    "Error while processing FreeMarker template", e);
        }
    }
}


模板文件中需要使用 ${}將java類中在Map對(duì)象中聲明的變量包圍起來就可以了

例如模板文件:
<pre>
//描述信息是 : ${message}
</pre>


則得到的結(jié)果是:
<pre>
//描述信息是 : Hello World!的的的的
</pre>



禮物 2008-09-17 00:00 發(fā)表評(píng)論
]]>
(轉(zhuǎn))FreeMarker中文參考手冊(cè)http://www.aygfsteel.com/libin2722/articles/229263.html禮物禮物Tue, 16 Sep 2008 13:56:00 GMThttp://www.aygfsteel.com/libin2722/articles/229263.htmlhttp://www.aygfsteel.com/libin2722/comments/229263.htmlhttp://www.aygfsteel.com/libin2722/articles/229263.html#Feedback0http://www.aygfsteel.com/libin2722/comments/commentRss/229263.htmlhttp://www.aygfsteel.com/libin2722/services/trackbacks/229263.html(1)模板 + 數(shù)據(jù)模型 = 輸出

FreeMarker基于設(shè)計(jì)者和程序員是具有不同專業(yè)技能的不同個(gè)體的觀念他們是分工勞動(dòng)的:設(shè)計(jì)者專注于表示——?jiǎng)?chuàng)建HTML文件、圖片、Web頁面的其它可視化方面;程序員創(chuàng)建系統(tǒng),生成設(shè)計(jì)頁面要顯示的數(shù)據(jù)。經(jīng)常會(huì)遇到的問題是:在Web頁面(或其它類型的文檔)中顯示的信息在設(shè)計(jì)頁面時(shí)是無效的,是基于動(dòng)態(tài)數(shù)據(jù)的。在這里,你可以在HTML(或其它要輸出的文本)中加入一些特定指令,F(xiàn)reeMarker會(huì)在輸出頁面給最終用戶時(shí),用適當(dāng)?shù)臄?shù)據(jù)替代這些代碼。

下面是一個(gè)例子:

<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
這個(gè)例子是在簡(jiǎn)單的HTML中加入了一些由${…}包圍的特定代碼,這些特定代碼是FreeMarker的指令,而包含F(xiàn)reeMarker的指令的文件就稱為模板(Template)。至于user、latestProduct.url和latestProduct.name來自于數(shù)據(jù)模型(data model)。數(shù)據(jù)模型由程序員編程來創(chuàng)建,向模板提供變化的信息,這些信息來自于數(shù)據(jù)庫、文件,甚至于在程序中直接生成。模板設(shè)計(jì)者不關(guān)心數(shù)據(jù)從那兒來,只知道使用已經(jīng)建立的數(shù)據(jù)模型。

下面是一個(gè)可能的數(shù)據(jù)模型:

(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse"
數(shù)據(jù)模型類似于計(jì)算機(jī)的文件系統(tǒng),latestProduct可以看作是目錄。

2、數(shù)據(jù)模型

(1)基礎(chǔ)

在快速入門中介紹了在模板中使用的三種基本對(duì)象類型:scalars、hashes 和sequences,其實(shí)還可以有其它更多的能力:

  • scalars:存儲(chǔ)單值
  • hashes:充當(dāng)其它對(duì)象的容器,每個(gè)都關(guān)聯(lián)一個(gè)唯一的查詢名字
  • sequences:充當(dāng)其它對(duì)象的容器,按次序訪問
  • 方法:通過傳遞的參數(shù)進(jìn)行計(jì)算,以新對(duì)象返回結(jié)果
  • 用戶自定義FTL標(biāo)記:宏和變換器

通常每個(gè)變量只具有上述的一種能力,但一個(gè)變量可以具有多個(gè)上述能力,如下面的例子:

(root)
|
+- mouse = "Yerri"
|
+- age = 12
|
+- color = "brown">
mouse既是scalars又是hashes,將上面的數(shù)據(jù)模型合并到下面的模板:
${mouse}       <#-- use mouse as scalar -->
${mouse.age}   <#-- use mouse as hash -->
${mouse.color} <#-- use mouse as hash -->
輸出結(jié)果是:
Yerri
12
brown

(2)Scalar變量

Scalar變量存儲(chǔ)單值,可以是:

  • 字符串:簡(jiǎn)單文本,在模板中使用引號(hào)(單引號(hào)或雙引號(hào))括起
  • 數(shù)字:在模板中直接使用數(shù)字值
  • 日期:存儲(chǔ)日期/時(shí)間相關(guān)的數(shù)據(jù),可以是日期、時(shí)間或日期-時(shí)間(Timestamp);通常情況,日期值由程序員加到數(shù)據(jù)模型中,設(shè)計(jì)者只需要顯示它們
  • 布爾值:true或false,通常在<#if …>標(biāo)記中使用

(3)hashes 、sequences和集合

有些變量不包含任何可顯示的內(nèi)容,而是作為容器包含其它變量,者有兩種類型:

  • hashes:具有一個(gè)唯一的查詢名字和它包含的每個(gè)變量相關(guān)聯(lián)
  • sequences:使用數(shù)字和它包含的每個(gè)變量相關(guān)聯(lián),索引值從0開始

集合變量通常類似sequences,除非無法訪問它的大小和不能使用索引來獲得它的子變量;集合可以看作只能由<#list …>指令使用的受限sequences

(4)方法

方法變量通常是基于給出的參數(shù)計(jì)算值。

下面的例子假設(shè)程序員已經(jīng)將方法變量avg放到數(shù)據(jù)模型中,用來計(jì)算數(shù)字平均值:

The average of 3 and 5 is: ${avg(3, 5)}
The average of 6 and 10 and 20 is: ${avg(6, 10, 20)}
The average of the price of python and elephant is:
${avg(animals.python.price, animals.elephant.price)}

(5)宏和變換器

宏和變換器變量是用戶自定義指令(自定義FTL標(biāo)記),會(huì)在后面講述這些高級(jí)特性

(6)節(jié)點(diǎn)

節(jié)點(diǎn)變量表示為樹型結(jié)構(gòu)中的一個(gè)節(jié)點(diǎn),通常在XML處理中使用,會(huì)在后面的專門章節(jié)中講

3、模板

(1)整體結(jié)構(gòu)

模板使用FTL(FreeMarker模板語言)編寫,是下面各部分的一個(gè)組合:

  • 文本:直接輸出
  • Interpolation:由${和},或#{和}來限定,計(jì)算值替代輸出
  • FTL標(biāo)記:FreeMarker指令,和HTML標(biāo)記類似,名字前加#予以區(qū)分,不會(huì)輸出
  • 注釋:由<#--和-->限定,不會(huì)輸出

下面是以一個(gè)具體模板例子:

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

注意事項(xiàng):

  • FTL區(qū)分大小寫,所以list是正確的FTL指令,而List不是;${name}和${NAME}是不同的
  • Interpolation只能在文本中使用
  • FTL標(biāo)記不能位于另一個(gè)FTL標(biāo)記內(nèi)部,例如:
<#if <#include 'foo'>='bar'>...</if>
  • 注釋可以位于FTL標(biāo)記和Interpolation內(nèi)部,如下面的例子:
<h1>Welcome ${user <#-- The name of user -->}!</h1>
<p>We have these animals:
<ul>
<#list <#-- some comment... --> animals as <#-- again... --> being>
...
  • 余的空白字符會(huì)在模板輸出時(shí)移除

(2)指令

在FreeMarker中,使用FTL標(biāo)記引用指令。有三種FTL標(biāo)記,這和HTML標(biāo)記是類似的:

  • 開始標(biāo)記:<#directivename parameters>
  • 結(jié)束標(biāo)記:</#directivename>
  • 空內(nèi)容指令標(biāo)記:<#directivename parameters/>

有兩種類型的指令:預(yù)定義指令和用戶定義指令。

用戶定義指令要使用@替換#,如<@mydirective>...</@mydirective>(會(huì)在后面講述)。

FTL標(biāo)記不能夠交叉,而應(yīng)該正確的嵌套,如下面的代碼是錯(cuò)誤的:

<ul>
<#list animals as being>
<li>${being.name} for ${being.price} Euros
<#if use = "Big Joe">
(except for you)
</#list>
</#if> <#-- WRONG! -->
</ul>
如果使用不存在的指令,F(xiàn)reeMarker不會(huì)使用模板輸出,而是產(chǎn)生一個(gè)錯(cuò)誤消息。

FreeMarker會(huì)忽略FTL標(biāo)記中的空白字符,如下面的例子:

<#list
animals       as
being
>
${being.name} for ${being.price} Euros
</#list    >
但是,<、</和指令之間不允許有空白字符。

(3)表達(dá)式

直接指定值

  • 字符串
使用單引號(hào)或雙引號(hào)限定

如果包含特殊字符需要轉(zhuǎn)義,如下面的例子:

${"It's \"quoted\" and
this is a backslash: \\"}
${'It\'s "quoted" and
this is a backslash: \\'}
輸出結(jié)果是:
It's "quoted" and
this is a backslash: \
It's "quoted" and
this is a backslash: \
下面是支持的轉(zhuǎn)義序列:

 

轉(zhuǎn)義序列 含義
\" 雙引號(hào)(u0022)
\' 單引號(hào)(u0027)
反斜杠(u005C)
\n 換行(u000A)
\r Return (u000D)
\t Tab (u0009)
\b Backspace (u0008)
\f Form feed (u000C)
\l <
\g >
\a &
\{ {
\xCode 4位16進(jìn)制Unicode代碼

 

有一類特殊的字符串稱為raw字符串,被認(rèn)為是純文本,其中的\和{等不具有特殊含義,該類字符串在引號(hào)前面加r,下面是一個(gè)例子:

${r"${foo}"}
${r"C:\foo\bar"}
輸出的結(jié)果是:
${foo}
C:\foo\bar
  • 數(shù)字

直接輸入,不需要引號(hào)

精度數(shù)字使用“.”分隔,不能使用分組符號(hào)

目前版本不支持科學(xué)計(jì)數(shù)法,所以“1E3”是錯(cuò)誤的

不能省略小數(shù)點(diǎn)前面的0,所以“.5”是錯(cuò)誤的

數(shù)字8、+8、08和8.00都是相同的

  • 布爾值

true和false,不使用引號(hào)

  • 序列

由逗號(hào)分隔的子變量列表,由方括號(hào)限定,下面是一個(gè)例子:

<#list ["winter", "spring", "summer", "autumn"] as x>
${x}
</#list>
輸出的結(jié)果是:
winter
spring
summer
autumn
列表的項(xiàng)目是表達(dá)式,所以可以有下面的例子:
[2 + 2, [1, 2, 3, 4], "whatnot"]
可以使用數(shù)字范圍定義數(shù)字序列,例如2..5等同于[2, 3, 4, 5],但是更有效率,注意數(shù)字范圍沒有方括號(hào)

可以定義反遞增的數(shù)字范圍,如5..2

  • 散列(hash)
由逗號(hào)分隔的鍵/值列表,由大括號(hào)限定,鍵和值之間用冒號(hào)分隔,下面是一個(gè)例子:
{"name":"green mouse", "price":150}
鍵和值都是表達(dá)式,但是鍵必須是字符串

獲取變量

  • 頂層變量: ${variable},變量名只能是字母、數(shù)字、下劃線、$、@和#的組合,且不能以數(shù)字開頭
  • 從散列中獲取數(shù)據(jù)

可以使用點(diǎn)語法或方括號(hào)語法,假設(shè)有下面的數(shù)據(jù)模型:

(root)
|
+- book
|   |
|   +- title = "Breeding green mouses"
|   |
|   +- author
|       |
|       +- name = "Julia Smith"
|       |
|       +- info = "Biologist, 1923-1985, Canada"
|
+- test = "title"
下面都是等價(jià)的:
book.author.name
book["author"].name
book.author.["name"]
book["author"]["name"]
使用點(diǎn)語法,變量名字有頂層變量一樣的限制,但方括號(hào)語法沒有該限制,因?yàn)槊质侨我獗磉_(dá)式的結(jié)果
  • 從序列獲得數(shù)據(jù):和散列的方括號(hào)語法語法一樣,只是方括號(hào)中的表達(dá)式值必須是數(shù)字;注意:第一個(gè)項(xiàng)目的索引是0

序列片斷:使用[startIndex..endIndex]語法,從序列中獲得序列片斷(也是序列);startIndex和endIndex是結(jié)果為數(shù)字的表達(dá)式

  • 特殊變量:FreeMarker內(nèi)定義變量,使用.variablename語法訪問

字符串操作

  • Interpolation(或連接操作)

可以使用${..}(或#{..})在文本部分插入表達(dá)式的值,例如:

${"Hello ${user}!"}
${"${user}${user}${user}${user}"}
可以使用+操作符獲得同樣的結(jié)果
${"Hello " + user + "!"}
${user + user + user + user}
${..}只能用于文本部分,下面的代碼是錯(cuò)誤的:
<#if ${isBig}>Wow!</#if>
<#if "${isBig}">Wow!</#if>
應(yīng)該寫成:
<#if isBig>Wow!</#if>
  • 子串

例子(假設(shè)user的值為“Big Joe”):

${user[0]}${user[4]}
${user[1..4]}
結(jié)果是(注意第一個(gè)字符的索引是0):
BJ
ig J
序列操作
  • 連接操作:和字符串一樣,使用+,下面是一個(gè)例子:
<#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>
- ${user}
</#list>
輸出結(jié)果是:
- Joe
- Fred
- Julia
- Kate
散列操作
  • 連接操作:和字符串一樣,使用+,如果具有相同的key,右邊的值替代左邊的值,例如:
<#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
- Joe is ${ages.Joe}
- Fred is ${ages.Fred}
- Julia is ${ages.Julia}
輸出結(jié)果是:
- Joe is 30
- Fred is 25
- Julia is 18
算術(shù)運(yùn)算
  • +、-、×、/、%,下面是一個(gè)例子:
${x * x - 100}
${x / 2}
${12 % 10}
輸出結(jié)果是(假設(shè)x為5):
-75
2.5
2
操作符兩邊必須是數(shù)字,因此下面的代碼是錯(cuò)誤的:
${3 * "5"} <#-- WRONG! -->
使用+操作符時(shí),如果一邊是數(shù)字,一邊是字符串,就會(huì)自動(dòng)將數(shù)字轉(zhuǎn)換為字符串,例如:
${3 + "5"}
輸出結(jié)果是:
35
使用內(nèi)建的int(后面講述)獲得整數(shù)部分,例如:
${(x/2)?int}
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}
輸出結(jié)果是(假設(shè)x為5):
2
1
1
-1
-1
  • 比較操作符

使用=(或==,完全相等)測(cè)試兩個(gè)值是否相等,使用!= 測(cè)試兩個(gè)值是否不相等

=和!=兩邊必須是相同類型的值,否則會(huì)產(chǎn)生錯(cuò)誤,例如<#if 1 = "1">會(huì)引起錯(cuò)誤

Freemarker是精確比較,所以對(duì)"x"、"x "和"X"是不相等的

對(duì)數(shù)字和日期可以使用<、<=、>和>=,但不能用于字符串

由于Freemarker會(huì)將>解釋成FTL標(biāo)記的結(jié)束字符,所以對(duì)于>和>=可以使用括號(hào)來避免這種情況,例如<#if (x > y)>

另一種替代的方法是,使用lt、lte、gt和gte來替代<、<=、>和>=

  • 邏輯操作符

&&(and)、||(or)、!(not),只能用于布爾值,否則會(huì)產(chǎn)生錯(cuò)誤

例子:

<#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>
  • 內(nèi)建函數(shù)

內(nèi)建函數(shù)的用法類似訪問散列的子變量,只是使用“?”替代“.”,下面列出常用的一些函數(shù)

    • 字符串使用的:

html:對(duì)字符串進(jìn)行HTML編碼

cap_first:使字符串第一個(gè)字母大寫

lower_case:將字符串轉(zhuǎn)換成小寫

upper_case:將字符串轉(zhuǎn)換成大寫

trim:去掉字符串前后的空白字符

    • 序列使用的:

size:獲得序列中元素的數(shù)目

    • 數(shù)字使用的:

int:取得數(shù)字的整數(shù)部分(如-1.9?int的結(jié)果是-1)

例子(假設(shè)test保存字符串"Tom & Jerry"):

${test?html}
${test?upper_case?html}
輸出結(jié)果是:
Tom &amp; Jerry
TOM &amp; JERRY
  • 操作符優(yōu)先順序

 

操作符組 操作符
后綴 [subvarName] [subStringRange] . (methodParams)
一元 +expr、-expr、!
內(nèi)建 ?
乘法 *、 / 、%
加法 +、-
關(guān)系 <、>、<=、>=(lt、lte、gt、gte)
相等 ==(=)、!=
邏輯and &&
邏輯or 雙豎線
數(shù)字范圍 ..

 

(4)Interpolation

Interpolation有兩種類型:

  1. 通用Interpolation:${expr}
  1. 數(shù)字Interpolation:#{expr}或#{expr; format}

注意:Interpolation只能用于文本部分

  • 通用Interpolation

插入字符串值:直接輸出表達(dá)式結(jié)果

插入數(shù)字值:根據(jù)缺省格式(由#setting指令設(shè)置)將表達(dá)式結(jié)果轉(zhuǎn)換成文本輸出;可以使用內(nèi)建函數(shù)string格式化單個(gè)Interpolation,下面是一個(gè)例子:

<#setting number_format="currency"/>
<#assign answer=42/>
${answer}
${answer?string}  <#-- the same as ${answer} -->
${answer?string.number}
${answer?string.currency}
${answer?string.percent}
輸出結(jié)果是:
$42.00
$42.00
42
$42.00
4,200%
插入日期值:根據(jù)缺省格式(由#setting指令設(shè)置)將表達(dá)式結(jié)果轉(zhuǎn)換成文本輸出;可以使用內(nèi)建函數(shù)string格式化單個(gè)Interpolation,下面是一個(gè)使用格式模式的例子:
${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')'")}
輸出的結(jié)果類似下面的格式:
2003-04-08 21:24:44 Pacific Daylight Time
Tue, Apr 8, '03
Tuesday, April 08, 2003, 09:24:44 PM (PDT)
插入布爾值:根據(jù)缺省格式(由#setting指令設(shè)置)將表達(dá)式結(jié)果轉(zhuǎn)換成文本輸出;可以使用內(nèi)建函數(shù)string格式化單個(gè)Interpolation,下面是一個(gè)例子:
<#assign foo=true/>
${foo?string("yes", "no")}
輸出結(jié)果是:
yes
  • 數(shù)字Interpolation的#{expr; format}形式可以用來格式化數(shù)字,format可以是:

mX:小數(shù)部分最小X位

MX:小數(shù)部分最大X位

例子:

<#-- If the language is US English the output is: -->
<#assign x=2.582/>
<#assign y=4/>
#{x; M2}   <#-- 2.58 -->
#{y; M2}   <#-- 4    -->
#{x; m1}   <#-- 2.6 -->
#{y; m1}   <#-- 4.0 -->
#{x; m1M2} <#-- 2.58 -->
#{y; m1M2} <#-- 4.0  -->

4、雜項(xiàng)

(1)用戶定義指令

宏和變換器變量是兩種不同類型的用戶定義指令,它們之間的區(qū)別是宏是在模板中使用macro指令定義,而變換器是在模板外由程序定義,這里只介紹宏

  • 基本用法

宏是和某個(gè)變量關(guān)聯(lián)的模板片斷,以便在模板中通過用戶定義指令使用該變量,下面是一個(gè)例子:

<#macro greet>
<font size="+2">Hello Joe!</font>
</#macro>
作為用戶定義指令使用宏變量時(shí),使用@替代FTL標(biāo)記中的#
<@greet></@greet>
如果沒有體內(nèi)容,也可以使用:
<@greet/>
  • 參數(shù)

在macro指令中可以在宏變量之后定義參數(shù),如:

<#macro greet person>
<font size="+2">Hello ${person}!</font>
</#macro>
可以這樣使用這個(gè)宏變量:
<@greet person="Fred"/> and <@greet person="Batman"/>
輸出結(jié)果是:
  <font size="+2">Hello Fred!</font>
and   <font size="+2">Hello Batman!</font>

宏的參數(shù)是FTL表達(dá)式,所以下面的代碼具有不同的意思:

<@greet person=Fred/>
這意味著將Fred變量的值傳給person參數(shù),該值不僅是字符串,還可以是其它類型,甚至是復(fù)雜的表達(dá)式

可以有多參數(shù),下面是一個(gè)例子:

<#macro greet person color>
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
可以這樣使用該宏變量:
<@greet person="Fred" color="black"/>
其中參數(shù)的次序是無關(guān)的,因此下面是等價(jià)的:
<@greet color="black" person="Fred"/>
只能使用在macro指令中定義的參數(shù),并且對(duì)所有參數(shù)賦值,所以下面的代碼是錯(cuò)誤的:
<@greet person="Fred" color="black" background="green"/>
<@greet person="Fred"/>
可以在定義參數(shù)時(shí)指定缺省值,如:
<#macro greet person color="black">
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
這樣<@greet person="Fred"/>就正確了

宏的參數(shù)是局部變量,只能在宏定義中有效

  • 嵌套內(nèi)容

用戶定義指令可以有嵌套內(nèi)容,使用<#nested>指令執(zhí)行指令開始和結(jié)束標(biāo)記之間的模板片斷

例子:

<#macro border>
<table border=4 cellspacing=0 cellpadding=4><tr><td>
<#nested>
</tr></td></table>
</#macro>
這樣使用該宏變量:
<@border>The bordered text</@border>
輸出結(jié)果:
  <table border=4 cellspacing=0 cellpadding=4><tr><td>
The bordered text
</tr></td></table>

<#nested>指令可以被多次調(diào)用,例如:

<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
<@do_thrice>
Anything.
</@do_thrice>
輸出結(jié)果:
  Anything.
Anything.
Anything.
嵌套內(nèi)容可以是有效的FTL,下面是一個(gè)有些復(fù)雜的例子: <@border> <ul> <@do_thrice> <li><@greet person="Joe"/> </@do_thrice> </ul> </@border> }}} 輸出結(jié)果:
  <table border=4 cellspacing=0 cellpadding=4><tr><td>
<ul>
<li><font size="+2">Hello Joe!</font>
<li><font size="+2">Hello Joe!</font>
<li><font size="+2">Hello Joe!</font>
</ul>
</tr></td></table>
宏定義中的局部變量對(duì)嵌套內(nèi)容是不可見的,例如:
<#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>
輸出結(jié)果:
    test 3/1: ? ? ?
test 3/2: ? ? ?
test 3/3: ? ? ?
  • 在宏定義中使用循環(huán)變量

用戶定義指令可以有循環(huán)變量,通常用于重復(fù)嵌套內(nèi)容,基本用法是:作為nested指令的參數(shù)傳遞循環(huán)變量的實(shí)際值,而在調(diào)用用戶定義指令時(shí),在<@…>開始標(biāo)記的參數(shù)后面指定循環(huán)變量的名字

例子:

<#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>
輸出結(jié)果:
  1. 0.5
2. 1
3. 1.5
4. 2 Last!

指定的循環(huán)變量的數(shù)目和用戶定義指令開始標(biāo)記指定的不同不會(huì)有問題

調(diào)用時(shí)少指定循環(huán)變量,則多指定的值不可見

調(diào)用時(shí)多指定循環(huán)變量,多余的循環(huán)變量不會(huì)被創(chuàng)建

(2)在模板中定義變量

在模板中定義的變量有三種類型:

  • plain變量:可以在模板的任何地方訪問,包括使用include指令插入的模板,使用assign指令創(chuàng)建和替換
  • 局部變量:在宏定義體中有效,使用local指令創(chuàng)建和替換
  • 循環(huán)變量:只能存在于指令的嵌套內(nèi)容,由指令(如list)自動(dòng)創(chuàng)建

宏的參數(shù)是局部變量,而不是循環(huán)變量;局部變量隱藏(而不是覆蓋)同名的plain變量;循環(huán)變量隱藏同名的局部變量和plain變量,下面是一個(gè)例子:

<#assign x = "plain">
1. ${x}  <#-- we see the plain var. here -->
<@test/>
6. ${x}  <#-- the value of plain var. was not changed -->
<#list ["loop"] as x>
7. ${x}  <#-- now the loop var. hides the plain var. -->
<#assign x = "plain2"> <#-- replace the plain var, hiding does not mater here -->
8. ${x}  <#-- it still hides the plain var. -->
</#list>
9. ${x}  <#-- the new value of plain var. -->
<#macro test>
2. ${x}  <#-- we still see the plain var. here -->
<#local x = "local">
3. ${x}  <#-- now the local var. hides it -->
<#list ["loop"] as x>
4. ${x}  <#-- now the loop var. hides the local var. -->
</#list>
5. ${x}  <#-- now we see the local var. again -->
</#macro>
輸出結(jié)果:
1. plain
2. plain
3. local
4. loop
5. local
6. plain
7. loop
8. loop
9. plain2

內(nèi)部循環(huán)變量隱藏同名的外部循環(huán)變量,如:

<#list ["loop 1"] as x>
${x}
<#list ["loop 2"] as x>
${x}
<#list ["loop 3"] as x>
${x}
</#list>
${x}
</#list>
${x}
</#list>
輸出結(jié)果:
  loop 1
loop 2
loop 3
loop 2
loop 1
模板中的變量會(huì)隱藏(而不是覆蓋)數(shù)據(jù)模型中同名變量,如果需要訪問數(shù)據(jù)模型中的同名變量,使用特殊變量global,下面的例子假設(shè)數(shù)據(jù)模型中的user的值是Big Joe:
<#assign user = "Joe Hider">
${user}          <#-- prints: Joe Hider -->
${.globals.user} <#-- prints: Big Joe -->

(3)名字空間

通常情況,只使用一個(gè)名字空間,稱為主名字空間

為了創(chuàng)建可重用的宏、變換器或其它變量的集合(通常稱庫),必須使用多名字空間,其目的是防止同名沖突

  • 創(chuàng)建庫

下面是一個(gè)創(chuàng)建庫的例子(假設(shè)保存在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指令導(dǎo)入庫到模板中,F(xiàn)reemarker會(huì)為導(dǎo)入的庫創(chuàng)建新的名字空間,并可以通過import指令中指定的散列變量訪問庫中的變量:
<#import "/lib/my_test.ftl" as my>
<#assign mail="fred@acme.com">
<@my.copyright date="1999-2002"/>
${my.mail}
${mail}
輸出結(jié)果:
  <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.
<br>Email: jsmith@acme.com</p>
jsmith@acme.com
fred@acme.com
可以看到例子中使用的兩個(gè)同名變量并沒有沖突,因?yàn)樗鼈兾挥诓煌拿挚臻g

可以使用assign指令在導(dǎo)入的名字空間中創(chuàng)建或替代變量,下面是一個(gè)例子:

<#import "/lib/my_test.ftl" as my>
${my.mail}
<#assign mail="jsmith@other.com" in my>
${my.mail}
輸出結(jié)果:
jsmith@acme.com
jsmith@other.com
數(shù)據(jù)模型中的變量任何地方都可見,也包括不同的名字空間,下面是修改的庫:
<#macro copyright date>
<p>Copyright (C) ${date} ${user}. All rights reserved.</p>
</#macro>
<#assign mail = "${user}@acme.com">
假設(shè)數(shù)據(jù)模型中的user變量的值是Fred,則下面的代碼:
<#import "/lib/my_test.ftl" as my>
<@my.copyright date="1999-2002"/>
${my.mail}
輸出結(jié)果:
  <p>Copyright (C) 1999-2002 Fred. All rights reserved.</p>
Fred@acme.com   


禮物 2008-09-16 21:56 發(fā)表評(píng)論
]]>
主站蜘蛛池模板: 重庆市| 信丰县| 杨浦区| 宜昌市| 太湖县| 郴州市| 大宁县| 余干县| 汉阴县| 健康| 清水河县| 漳平市| 鸡东县| 昌图县| 灵台县| 韶关市| 楚雄市| 肥城市| 育儿| 水富县| 微山县| 常熟市| 静乐县| 稻城县| 平阴县| 崇文区| 上杭县| 格尔木市| 开封县| 安康市| 泗水县| 昭平县| 冀州市| 北票市| 开封市| 康定县| 威信县| 韶关市| 东兴市| 南宁市| 古浪县|