SlideShare una empresa de Scribd logo
1 de 10
Descargar para leer sin conexión
首页    新闻    论坛   问答      博客     招聘       更多 ▼                                                          您 还 未登 录   !   我的应用       登录     注册




     备忘收集                                                                                                                  永久域名 http://jiangsha.javaeye.com


                                                                                                 240多个jQuery插件   |   创建oracle数据库连接(database link)的两 ...
                                      2009-04-22

                                      Freemarker页 面 语 法
                                     文章分 类 :Web前端


                                      A 概念
                                      最常用的    3 个概念
        jiangsha
                                      sequence 序列,对应java 里的 list 、数组等非键值对的集合
浏览: 26429 次
                                      hash 键值对的集合
性别:                                   namespace 对一个ftl 文件的引用 , 利用这个名字可以访问到该 ftl 文件的资源

来自: 北京
                                      B 指令
                                      if, else, elseif
                                     语法
    详细资料              留言簿
                                         Java代 码
搜索本博客                                      1.   <#if condition>
                                           2.     ...
                           搜索
                                           3.   <#elseif condition2>
                                           4.     ...
最近 访 客               >>更多访客                5.   <#elseif condition3>
                                           6.     ...
                                           7.   ...
                                           8.   <#else>
                                           9.     ...
magiclife345 zhaocan1                     10.   </#if>
                                     用例

                                         Freemarker代 码
                                           1.   <#if x = 1>
hardPass        liubinwang2009             2.    x is 1
                                           3.   </#if>
                                           4.   <#if x = 1>
博客分 类                                      5.    x is 1
  全部博客 (40)                                6.   <#else>
                                           7.    x is not 1
  JSP (2)                                  8.   </#if>
  Javascript (3)
                                      switch, case, default, break
  Java (4)
                                     语法
  Fckeditor (3)
  JQUERY (2)                             Freemarker代 码
                                           1.   <#sw itch value>
  EL表达式 (1)                                2.    <#case refValue1>
  Freemarker (5)                           3.         ...
                                           4.         <#break>
  Hibernate (1)                            5.    <#case refValue2>
  数据库 (3)                                  6.         ...
                                           7.         <#break>
  文件资源 (3)                                 8.    ...
  模板 (1)
                                           9.    <#case refValueN>
                                          10.         ...
                                          11.         <#break>
我的留言簿                >>更多留言               12.    <#default>
  http://sfeve.javaeye.com/blog/796110    13.         ...
  这个是我 ...                                14.   </#sw itch>

  -- by sfeve
                                     用例
                                      字符串
其他分 类
                                         Freemarker代 码
  我的收藏 (44)
                                           1.   <#sw itch being.size>
  我的论坛主题贴 (0)                              2.    <#case "small">
                                           3.          This w ill be processed if it is small
  我的所有论坛贴 (68)
                                           4.          <#break>
  我的精华良好贴 (0)                              5.    <#case "medium">
                                           6.          This w ill be processed if it is medium


                                                                                                                             converted by Web2PDFConvert.com
最近加入圈子                      7.           <#break>
                            8.     <#case "large">
Cetia4 REST Framework
                            9.           This w ill be processed if it is large
rapid-framework            10.           <#break>
                           11.     <#default>
FreeMarker                 12.           This w ill be processed if it is neither
                           13.    </#sw itch>
存档
2010-12 (2)             数字

2010-11 (4)              Freemarker代 码

2010-06 (1)                  1.   <#sw itch x>
                             2.    <#case x = 1>
更多存档...                      3.         1
                             4.    <#case x = 2>
评论 排行榜                       5.         2
                             6.    <#default>
MyEclipse7.5下手动安
                             7.         d
装freemarker ide插件            8.   </#sw itch>
Java反射学习
                        如果x=1 输出 1 2, x=2 输出       2, x=3 输出d
免安装版Tomcat6.0启动方法
                        list, break
需求用例模板
                        语法
oracle pl/sql 存储过程(抄)
                         Freemarker代 码
                             1.   <#list sequence as item>
                             2.   ...
                             3.   <#if item = "spring"><#break></#if>
                             4.   ...
                             5.   </#list>
                        关键字

                        item_index:是list当前值的下标

                        item_has_next:判断list是否还有值
                        用例
                         Freemarker代 码
                             1.   <#assign seq = ["w inter", "spring", "summer", "autumn"]>
                             2.   <#list seq as x>
                             3.    ${x_index + 1}. ${x}<#if x_has_next>,</#if>
                             4.   </#list>

                        输出:
                          1.winter,
                          2.spring,
                          3.summer,
                          4.autumn
                        include
                        语法
                         Freemarker代 码
                             1.   <#include filename>
                        或则
                         Java代 码
                             1.   <#include filename options>

                        options包含两个属性

                        encoding="GBK" 编码格式

                        parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值
                        的如parse=true,而不是parse="true"
                        用例
                        /common/copyright.ftl 包含内容
                         Ftl代 码
                             1.   Copyright 2001-2002 ${me}
                             2.
                             3.   All rights reserved.

                        模板文件




                                                                                              converted by Web2PDFConvert.com
Java代 码
     1.     <#assign me = "Juila Smith">
     2.
     3.     Some test
     4.
     5.     Yeah
     6.     ___________________________________________________________________________
     7.
     8.     <span><strong><span><#include "/common/copyright.ftl" encoding="GBK"></span>
     9.
    10.
    11.
    12.
    13.
    14.     </strong>
    15.
    16.
    17.
    18.     </span>



输出结果:
Some test

Yeah.

Copyright 2001-2002 Juila Smith

All rights reserved.


Import
语法
  Freemarker代 码
     1.     <#import path as hash>
类似于java里的import,它导入文件,然后就可以在当前文件里使用被导入文件里的宏组件
用例
假设mylib.ftl 里定义了宏 copyright 那么我们在其他模板页面里可以这样使用
  Freemarker代 码
     1.     <#import "/libs/mylib.ftl" as my>
     2.
     3.     <@my.copyright date="1999-2002"/>
     4.
     5.     <#-- "my"在freemarker里被称作namespace -->


compress
语法
  Freemarker代 码
     1.     <#compress>
     2.      ...
     3.     </#compress>

用来压缩空白空间和空白的行

escape, noescape
语法
  Freemarker代 码
     1.     <#escape identifier as expression>
     2.      ...
     3.      <#noescape>...</#noescape>
     4.      ...
     5.     </#escape>
用例
   主要使用在相似的字符串变量输出,比如某一个模块的所有字符串输出都必须是html安全的,这个时候就可以使用
该表达式
  Freemarker代 码
     1.     <#escape x as x?html>
     2.      First name: ${firstName}
     3.      <#noescape>Last name: ${lastName}</#noescape>
     4.      Maiden name: ${maidenName}


                                                                                     converted by Web2PDFConvert.com
5.   </#escape>
相同表达式
 Ftl代 码
     1.   First name: ${firstName?html}
     2.   Last name: ${lastName }
     3.   Maiden name: ${maidenName?html}


assign
语法
 Freemarker代 码
   1.     <#assign name=value>
   2.
   3.     <#-- 或则 -->
   4.
   5.     <#assign name1=value1 name2=value2 ... nameN=valueN>
   6.
   7.     <#-- 或则 -->
   8.
   9.     <#assign same as above... in namespacehash>
  10.
  11.     <#-- 或则 -->
  12.
  13.     <#assign name>
  14.      capture this
  15.     </#assign>
  16.
  17.     <#-- 或则 -->
  18.
  19.     <#assign name in namespacehash>
  20.      capture this
  21.     </#assign>

用例
生成变量,并且给变量赋值


给seasons赋予序列值
 Ftl代 码
     1.   <#assign seasons = ["w inter", "spring", "summer", "autumn"]>
给变量test加1
 Ftl代 码
     1.   <#assign test = test + 1>
给my namespage 赋予一个变量bgColor,下面可以通过my.bgColor来访问这个变量
 Ftl代 码
     1.   <#import "/mylib.ftl" as my>
     2.
     3.   <#assign bgColor="red" in my>
将一段输出的文本作为变量保存在x里
 Ftl代 码
   1.     <#assign x>
   2.      <#list 1..3 as n>
   3.           ${n} <@myMacro />
   4.      </#list>
   5.     </#assign>
   6.
   7.     Number of w ords: ${x?w ord_list?size}
   8.
   9.     ${x}
  10.
  11.     <#assign x>Hello ${user}!</#assign>         error
  12.
  13.     <#assign x=" Hello ${user}!">        true
同 时 也支持中文 赋值 ,如:
 Ftl代 码
     1.   <#assign 语法>
     2.    java
     3.   </#assign>
     4.
     5.   ${ 语法}
打印输出:


                                                                          converted by Web2PDFConvert.com
java


global
语法
  Freemarker代 码
        1.   <#global name=value>
        2.
        3.   <#--或则-->
        4.
        5.   <#global name1=value1 name2=value2 ... nameN=valueN>
        6.
        7.   <#--或则-->
        8.
        9.   <#global name>
       10.    capture this
       11.   </#global>

  全局赋值语法,利用这个语法给变量赋值,那么这个变量在所有的namespace                            [A1] 中是可见的, 如果这个变量被当前的 assign 语法
覆盖 如<#global x=2> <#assign x=1> 在当前页面里x=2 将被隐藏,或者通过 ${.global.x} 来访问

setting
语法
  Freemarker代 码
        1.   <#setting name=value>

用来设置整个系统的一个环境
locale
number_format
boolean_format
date_format , time_format , datetime_format
time_zone
classic_compatible
用例
假如当前是匈牙利的设置,然后修改成美国
  Ftl代 码
        1.   ${1.2}
        2.
        3.   <#setting locale="en_US">
        4.
        5.   ${1.2}

输出
       1,2

       1.2
因为匈牙利是采用", "作为十进制的分隔符,美国是用" . "

macro, nested, return
语法
  Freemarker代 码
        1.   <#macro name param1 param2 ... paramN>
        2.    ...
        3.    <#nested loopvar1, loopvar2, ..., loopvarN>
        4.    ...
        5.    <#return>
        6.    ...
        7.   </#macro>
用例
  Ftl代 码
        1.   <#macro test foo bar="Bar"[A2] baaz=-1>
        2.    Test text, and the params: ${foo}, ${bar}, ${baaz}
        3.   </#macro>
        4.
        5.   <@test foo="a" bar="b" baaz=5*5-2/>
        6.
        7.   <@test foo="a" bar="b"/>
        8.
        9.   <@test foo="a" baaz=5*5-2/>
       10.
       11.   <@test foo="a"/>


                                                                               converted by Web2PDFConvert.com
输出
 T text, and the params: a, b, 23
  est
 T text, and the params: a, b, -1
  est
 T text, and the params: a, Bar, 23
  est
 T text, and the params: a, Bar, -1
  est

定义循环输出的宏
  Ftl代 码
      1.      <#macro list title items>
      2.      ${title?cap_first}:
      3.             <#list items as x>
      4.               *${x?cap_first}
      5.
      6.           </#list>
      7.      </#macro>
      8.
      9.      <@list items=["mouse", "elephant", "python"] title="Animals"/>

输出结果:
   Animals:
      *Mouse
      *Elephant
      *Python

包含body 的宏
  Ftl代 码
      1.      <#macro repeat count>
      2.       <#list 1..count as x>
      3.            <#nested x, x/2, x==count>
      4.       </#list>
      5.      </#macro>
      6.
      7.      <@repeat count=4 ; c halfc last>
      8.       ${c}. ${halfc}<#if last> Last!</#if>
      9.      </@repeat>

输出
 1. 0.5
 2. 1
 3. 1.5
 4. 2 Last!
t, lt, rt
语法
  Freemarkder代 码
      1.      <#t> 去掉左右空白和回车换行
      2.
      3.      <#lt> 去掉左边空白和回车换行
      4.
      5.      <#rt> 去掉右边空白和回车换行
      6.
      7.      <#nt> 取消上面的效果

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")?html} 如果var is null 那么将会被 hello world 替代
     判断对象是不是                 null

  Ftl代 码
      1.      <#if mouse?exists>
      2.          Mouse found
      3.      <#else>


                                                                               converted by Web2PDFConvert.com
也可以直接${mouse?if_exists})输出布尔形


--------------------------------------------
(1)解决输出中文乱码问题:
  freemarker乱码的原因:
     没有使用正确的编码格式读取模版文件,表现为模版中的中文为乱码


 解决方法:在classpath上放置一个文件freemarker.properties,在里面写上模版文件的编码方式,比如
 default_encoding=UTF-8
 locale=zh_CN
 注意:eclipse中除了xml文件、java文件外,默认的文件格式iso8859-1

    数据插入模版时,没有使用正确的编码,表现出模版中的新插入数据为乱码


 解决方法:在result的配置中,指定charset,s2的FreemarkerResult.java会将charset传递freemarker

 <action name="ListPersons" class="ListPersons">

 <result type="freemarker">
    <param name="location">/pages/Person/view.ftl</param>
    <param name="contentType"> text/html;charset=UTF-8
 </param>
 </result>
 </action>

(2)提高freemarker的性能

 在freemarker.properties中设置:
 template_update_delay=60000
 避免每次请求都重新载入模版,即充分利用cached的模版

(3)尽量使用freemarker本身的提供的tag,使用S2 tags 的标签会在性能上有所损失


(4)freemarker的标签种类:
    ${..}:FreeMarker will replace it in the output with the actual value of the thing in the curly brackets. They are called interpolation
    s.
    # ,代表是FTL tags( FreeMarker Template Language tags) ,hey are instructions to FreeMarker and will not be printed to the
    output
           <#if ...></#if>
           <#list totalList as elementObject>...</#list>

    @ ,代表用户自定义的标签
    <#-- --> 注释标签,注意不是<!-- -->

(5)一些特殊的指令:
    r代表原样输出:${r"C:foobar"}
    <#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list>
    ?引出内置指令
          String处理指令:
                html:特殊的html字符将会被转义,比如"<",处理后的结果是&lt;
                cap_first 、lower_case 、upper_case
                trim :除去字符串前后的空格

          sequences处理指令
              size :返回sequences的大小

          numbers处理指令
              int:number的整数部分,(e.g. -1.9?int is -1)

(6)对于null,或者miss value,freemarker会报错
     ?exists:旧版本的用法
    !:default value operator,语法结构为: unsafe_expr !default_expr,比如 ${mouse!"No mouse."} 当mouse不存
    在时,返回default value;
        (product.color)!"red" 这种方式,能够处理product或者color为miss value的情况;
        而product.color!"red"将只处理color为miss value的情况


    ??: Missing value test operator ,测试是否为missing value
         unsafe_expr ?? :product.color??将只测试color是否为null
         (unsafe_expr )??:(product.color)??将测试product和color是否存在null

 Ftl代 码
    1.    <#if mouse??>
    2.     Mouse found
    3.    <#else>
    4.     No mouse found
    5.    </#if>


                                                                                                     converted by Web2PDFConvert.com
6.     Creating mouse...
    7.     <#assign mouse = "Jerry">
    8.     <#if mouse??>
    9.      Mouse found
   10.
   11.     <#else>
   12.      No mouse found
   13.     </#if>

(7)模版 值 插入方式 (interpolation)
   模版
    通用方式 ( Universal interpolations ):       ${expression }

    对于字符串:只是简单输出
    对于数值,会自动根据local确定格式,称为human                      audience,否则称为computer audience,可以"?c", 比如, <a
    href="/shop/details?id=${product.id ?c }">Details...</a>,因此这里的id是给浏览器使用的,不需要进行格式化,注意?c只对数值
    有效
    对于日期,会使用默认的日期格式转换,因此需要事先设置好默认的转换格式,包括date_format                                    , time_format
    ,atetime_format
    对于布尔值,不能输出,会报错并停止模版的执行,比如${a                               = 2} 会出错,但是可以 string built-in来进行转换

数 值处 理,具体参考: Built-ins for numbers
 http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number

 数值处理的例子:

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

 除了使用内置的formate,可以使用任何用Java decimal number format syntax 书写的formate,比如


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

 更加方便的格式:


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

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



 日期处理,参考Built-ins for dates


 http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date

 日期处理的例子:
         ${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}


注意:




                                                                                     converted by Web2PDFConvert.com
由于java语言中的Date类型的不足,freemarker不能根据Date变量判断出变量包含的部分(日期、时间还是全部),在这种情
况下,freemarker


  不能正确显示出${lastUpdated?string.short} 或者 simply ${lastUpdated},因此,可以通过?date, ?time and ?datetime built-ins


  来帮助freemarker来进行判断,比如${lastUpdated?datetime?string.short}


  除了使用内置的日期转换格式外,可以自己指定日期的格式,使用的是Java date format syntax,比如:
          ${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')'")}

  数 值专 用方式 ( Numerical interpolations ):#{expression     } or #{expression ; format },这是数值专用的输出方式,但是
最好使用通用方式的string               built-in或者number_format 来完成转换,Numerical interpolations 方式将会被停用


(8)创建自定义模版
  Ftl代 码
     1.      <#macro greet>
     2.         <font size="+2">Hello Joe!</font>
     3.      </#macro>




<#assign user="zhangsan"/>
字符串连接
${"Hello ${user}!"} 与 ${"Hello " + user + "!"} 相同
结果:Hello zhangsan
获取字符
${user[0]} ${user[4]}
结果:z g
序列的连接和访问
<#assign nums=["1" , "2"] + ["3" , "4"] />
${nums[0]} 结果是 1
内置函数
html 使用实体引用替换字符串中所有HTML字符,例如,使用&amp; 替换&
lower_case 将字符串转化成小写
substring
index_of 例如”abcdc"?index_of("bc") 将返回1
seq_contains 序列中是否包含指定值 ${nums?seq_contains("1")?string("yes","no")}
seq_index_of 第一个出现的索引 ${nums?seq_index_of("1")} 结果0
sort_by 用于散列




                                                             240多个jQuery插件       |   创建oracle数据库连接(database link)的两 ...

09:59      浏览 (3931)       评论 (1)       分类: Freemarker      相关推荐



  评论
   1 楼 zhousheng193 2010-08-13 引用
   值得学习,非常感谢!




  发 表 评论
                                    B    I   U   Quote    C ode   List   Img   URL   Flash   Table
              表情 图标               字体颜色: 标准                  字体大小: 标准                   对齐: 标准


                                    提示:选择您需要装饰的文字, 按上列按钮即可添加上相应的标签




                                                                                               converted by Web2PDFConvert.com
您还没有登录,请登录后发表评论(快捷键 Alt+S / Ctrl+Enter) 提交




声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。若作者同意转载,必须以超链接形式标明文章原始出处和作者。
            © 2003-2010 JavaEye.com. All rights reserved. 上海炯耐计算机软件有限公司 [ 沪ICP备05023328号 ]




                                                                               converted by Web2PDFConvert.com

Más contenido relacionado

Más de isnull

张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式isnull
 
杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享isnull
 
Barcelona apc mem2010
Barcelona apc mem2010Barcelona apc mem2010
Barcelona apc mem2010isnull
 
Mysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimizationMysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimizationisnull
 
Designofhtml5
Designofhtml5Designofhtml5
Designofhtml5isnull
 
Mysql开发与优化
Mysql开发与优化Mysql开发与优化
Mysql开发与优化isnull
 
我的Ubuntu之旅
我的Ubuntu之旅我的Ubuntu之旅
我的Ubuntu之旅isnull
 
软件工程&架构
软件工程&架构软件工程&架构
软件工程&架构isnull
 
淘宝分布式数据处理实践
淘宝分布式数据处理实践淘宝分布式数据处理实践
淘宝分布式数据处理实践isnull
 
阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训isnull
 
183银行服务器下载说明
183银行服务器下载说明183银行服务器下载说明
183银行服务器下载说明isnull
 
人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析isnull
 
Data on the web
Data on the webData on the web
Data on the webisnull
 
Tsung
Tsung Tsung
Tsung isnull
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010isnull
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opmisnull
 
Yui3 初探
Yui3 初探Yui3 初探
Yui3 初探isnull
 
大型应用软件架构的变迁
大型应用软件架构的变迁大型应用软件架构的变迁
大型应用软件架构的变迁isnull
 

Más de isnull (20)

张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式
 
杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享
 
Barcelona apc mem2010
Barcelona apc mem2010Barcelona apc mem2010
Barcelona apc mem2010
 
Mysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimizationMysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimization
 
Designofhtml5
Designofhtml5Designofhtml5
Designofhtml5
 
Mysql开发与优化
Mysql开发与优化Mysql开发与优化
Mysql开发与优化
 
我的Ubuntu之旅
我的Ubuntu之旅我的Ubuntu之旅
我的Ubuntu之旅
 
软件工程&架构
软件工程&架构软件工程&架构
软件工程&架构
 
淘宝分布式数据处理实践
淘宝分布式数据处理实践淘宝分布式数据处理实践
淘宝分布式数据处理实践
 
阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训
 
Scrum
ScrumScrum
Scrum
 
Scrum
ScrumScrum
Scrum
 
183银行服务器下载说明
183银行服务器下载说明183银行服务器下载说明
183银行服务器下载说明
 
人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析
 
Data on the web
Data on the webData on the web
Data on the web
 
Tsung
Tsung Tsung
Tsung
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opm
 
Yui3 初探
Yui3 初探Yui3 初探
Yui3 初探
 
大型应用软件架构的变迁
大型应用软件架构的变迁大型应用软件架构的变迁
大型应用软件架构的变迁
 

Freemarker页面语法

  • 1. 首页 新闻 论坛 问答 博客 招聘 更多 ▼ 您 还 未登 录 ! 我的应用 登录 注册 备忘收集 永久域名 http://jiangsha.javaeye.com 240多个jQuery插件 | 创建oracle数据库连接(database link)的两 ... 2009-04-22 Freemarker页 面 语 法 文章分 类 :Web前端 A 概念 最常用的 3 个概念 jiangsha sequence 序列,对应java 里的 list 、数组等非键值对的集合 浏览: 26429 次 hash 键值对的集合 性别: namespace 对一个ftl 文件的引用 , 利用这个名字可以访问到该 ftl 文件的资源 来自: 北京 B 指令 if, else, elseif 语法 详细资料 留言簿 Java代 码 搜索本博客 1. <#if condition> 2. ... 搜索 3. <#elseif condition2> 4. ... 最近 访 客 >>更多访客 5. <#elseif condition3> 6. ... 7. ... 8. <#else> 9. ... magiclife345 zhaocan1 10. </#if> 用例 Freemarker代 码 1. <#if x = 1> hardPass liubinwang2009 2. x is 1 3. </#if> 4. <#if x = 1> 博客分 类 5. x is 1 全部博客 (40) 6. <#else> 7. x is not 1 JSP (2) 8. </#if> Javascript (3) switch, case, default, break Java (4) 语法 Fckeditor (3) JQUERY (2) Freemarker代 码 1. <#sw itch value> EL表达式 (1) 2. <#case refValue1> Freemarker (5) 3. ... 4. <#break> Hibernate (1) 5. <#case refValue2> 数据库 (3) 6. ... 7. <#break> 文件资源 (3) 8. ... 模板 (1) 9. <#case refValueN> 10. ... 11. <#break> 我的留言簿 >>更多留言 12. <#default> http://sfeve.javaeye.com/blog/796110 13. ... 这个是我 ... 14. </#sw itch> -- by sfeve 用例 字符串 其他分 类 Freemarker代 码 我的收藏 (44) 1. <#sw itch being.size> 我的论坛主题贴 (0) 2. <#case "small"> 3. This w ill be processed if it is small 我的所有论坛贴 (68) 4. <#break> 我的精华良好贴 (0) 5. <#case "medium"> 6. This w ill be processed if it is medium converted by Web2PDFConvert.com
  • 2. 最近加入圈子 7. <#break> 8. <#case "large"> Cetia4 REST Framework 9. This w ill be processed if it is large rapid-framework 10. <#break> 11. <#default> FreeMarker 12. This w ill be processed if it is neither 13. </#sw itch> 存档 2010-12 (2) 数字 2010-11 (4) Freemarker代 码 2010-06 (1) 1. <#sw itch x> 2. <#case x = 1> 更多存档... 3. 1 4. <#case x = 2> 评论 排行榜 5. 2 6. <#default> MyEclipse7.5下手动安 7. d 装freemarker ide插件 8. </#sw itch> Java反射学习 如果x=1 输出 1 2, x=2 输出 2, x=3 输出d 免安装版Tomcat6.0启动方法 list, break 需求用例模板 语法 oracle pl/sql 存储过程(抄) Freemarker代 码 1. <#list sequence as item> 2. ... 3. <#if item = "spring"><#break></#if> 4. ... 5. </#list> 关键字 item_index:是list当前值的下标 item_has_next:判断list是否还有值 用例 Freemarker代 码 1. <#assign seq = ["w inter", "spring", "summer", "autumn"]> 2. <#list seq as x> 3. ${x_index + 1}. ${x}<#if x_has_next>,</#if> 4. </#list> 输出: 1.winter, 2.spring, 3.summer, 4.autumn include 语法 Freemarker代 码 1. <#include filename> 或则 Java代 码 1. <#include filename options> options包含两个属性 encoding="GBK" 编码格式 parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值 的如parse=true,而不是parse="true" 用例 /common/copyright.ftl 包含内容 Ftl代 码 1. Copyright 2001-2002 ${me} 2. 3. All rights reserved. 模板文件 converted by Web2PDFConvert.com
  • 3. Java代 码 1. <#assign me = "Juila Smith"> 2. 3. Some test 4. 5. Yeah 6. ___________________________________________________________________________ 7. 8. <span><strong><span><#include "/common/copyright.ftl" encoding="GBK"></span> 9. 10. 11. 12. 13. 14. </strong> 15. 16. 17. 18. </span> 输出结果: Some test Yeah. Copyright 2001-2002 Juila Smith All rights reserved. Import 语法 Freemarker代 码 1. <#import path as hash> 类似于java里的import,它导入文件,然后就可以在当前文件里使用被导入文件里的宏组件 用例 假设mylib.ftl 里定义了宏 copyright 那么我们在其他模板页面里可以这样使用 Freemarker代 码 1. <#import "/libs/mylib.ftl" as my> 2. 3. <@my.copyright date="1999-2002"/> 4. 5. <#-- "my"在freemarker里被称作namespace --> compress 语法 Freemarker代 码 1. <#compress> 2. ... 3. </#compress> 用来压缩空白空间和空白的行 escape, noescape 语法 Freemarker代 码 1. <#escape identifier as expression> 2. ... 3. <#noescape>...</#noescape> 4. ... 5. </#escape> 用例 主要使用在相似的字符串变量输出,比如某一个模块的所有字符串输出都必须是html安全的,这个时候就可以使用 该表达式 Freemarker代 码 1. <#escape x as x?html> 2. First name: ${firstName} 3. <#noescape>Last name: ${lastName}</#noescape> 4. Maiden name: ${maidenName} converted by Web2PDFConvert.com
  • 4. 5. </#escape> 相同表达式 Ftl代 码 1. First name: ${firstName?html} 2. Last name: ${lastName } 3. Maiden name: ${maidenName?html} assign 语法 Freemarker代 码 1. <#assign name=value> 2. 3. <#-- 或则 --> 4. 5. <#assign name1=value1 name2=value2 ... nameN=valueN> 6. 7. <#-- 或则 --> 8. 9. <#assign same as above... in namespacehash> 10. 11. <#-- 或则 --> 12. 13. <#assign name> 14. capture this 15. </#assign> 16. 17. <#-- 或则 --> 18. 19. <#assign name in namespacehash> 20. capture this 21. </#assign> 用例 生成变量,并且给变量赋值 给seasons赋予序列值 Ftl代 码 1. <#assign seasons = ["w inter", "spring", "summer", "autumn"]> 给变量test加1 Ftl代 码 1. <#assign test = test + 1> 给my namespage 赋予一个变量bgColor,下面可以通过my.bgColor来访问这个变量 Ftl代 码 1. <#import "/mylib.ftl" as my> 2. 3. <#assign bgColor="red" in my> 将一段输出的文本作为变量保存在x里 Ftl代 码 1. <#assign x> 2. <#list 1..3 as n> 3. ${n} <@myMacro /> 4. </#list> 5. </#assign> 6. 7. Number of w ords: ${x?w ord_list?size} 8. 9. ${x} 10. 11. <#assign x>Hello ${user}!</#assign> error 12. 13. <#assign x=" Hello ${user}!"> true 同 时 也支持中文 赋值 ,如: Ftl代 码 1. <#assign 语法> 2. java 3. </#assign> 4. 5. ${ 语法} 打印输出: converted by Web2PDFConvert.com
  • 5. java global 语法 Freemarker代 码 1. <#global name=value> 2. 3. <#--或则--> 4. 5. <#global name1=value1 name2=value2 ... nameN=valueN> 6. 7. <#--或则--> 8. 9. <#global name> 10. capture this 11. </#global> 全局赋值语法,利用这个语法给变量赋值,那么这个变量在所有的namespace [A1] 中是可见的, 如果这个变量被当前的 assign 语法 覆盖 如<#global x=2> <#assign x=1> 在当前页面里x=2 将被隐藏,或者通过 ${.global.x} 来访问 setting 语法 Freemarker代 码 1. <#setting name=value> 用来设置整个系统的一个环境 locale number_format boolean_format date_format , time_format , datetime_format time_zone classic_compatible 用例 假如当前是匈牙利的设置,然后修改成美国 Ftl代 码 1. ${1.2} 2. 3. <#setting locale="en_US"> 4. 5. ${1.2} 输出 1,2 1.2 因为匈牙利是采用", "作为十进制的分隔符,美国是用" . " macro, nested, return 语法 Freemarker代 码 1. <#macro name param1 param2 ... paramN> 2. ... 3. <#nested loopvar1, loopvar2, ..., loopvarN> 4. ... 5. <#return> 6. ... 7. </#macro> 用例 Ftl代 码 1. <#macro test foo bar="Bar"[A2] baaz=-1> 2. Test text, and the params: ${foo}, ${bar}, ${baaz} 3. </#macro> 4. 5. <@test foo="a" bar="b" baaz=5*5-2/> 6. 7. <@test foo="a" bar="b"/> 8. 9. <@test foo="a" baaz=5*5-2/> 10. 11. <@test foo="a"/> converted by Web2PDFConvert.com
  • 6. 输出 T text, and the params: a, b, 23 est T text, and the params: a, b, -1 est T text, and the params: a, Bar, 23 est T text, and the params: a, Bar, -1 est 定义循环输出的宏 Ftl代 码 1. <#macro list title items> 2. ${title?cap_first}: 3. <#list items as x> 4. *${x?cap_first} 5. 6. </#list> 7. </#macro> 8. 9. <@list items=["mouse", "elephant", "python"] title="Animals"/> 输出结果: Animals: *Mouse *Elephant *Python 包含body 的宏 Ftl代 码 1. <#macro repeat count> 2. <#list 1..count as x> 3. <#nested x, x/2, x==count> 4. </#list> 5. </#macro> 6. 7. <@repeat count=4 ; c halfc last> 8. ${c}. ${halfc}<#if last> Last!</#if> 9. </@repeat> 输出 1. 0.5 2. 1 3. 1.5 4. 2 Last! t, lt, rt 语法 Freemarkder代 码 1. <#t> 去掉左右空白和回车换行 2. 3. <#lt> 去掉左边空白和回车换行 4. 5. <#rt> 去掉右边空白和回车换行 6. 7. <#nt> 取消上面的效果 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")?html} 如果var is null 那么将会被 hello world 替代 判断对象是不是 null Ftl代 码 1. <#if mouse?exists> 2. Mouse found 3. <#else> converted by Web2PDFConvert.com
  • 7. 也可以直接${mouse?if_exists})输出布尔形 -------------------------------------------- (1)解决输出中文乱码问题: freemarker乱码的原因: 没有使用正确的编码格式读取模版文件,表现为模版中的中文为乱码 解决方法:在classpath上放置一个文件freemarker.properties,在里面写上模版文件的编码方式,比如 default_encoding=UTF-8 locale=zh_CN 注意:eclipse中除了xml文件、java文件外,默认的文件格式iso8859-1 数据插入模版时,没有使用正确的编码,表现出模版中的新插入数据为乱码 解决方法:在result的配置中,指定charset,s2的FreemarkerResult.java会将charset传递freemarker <action name="ListPersons" class="ListPersons"> <result type="freemarker"> <param name="location">/pages/Person/view.ftl</param> <param name="contentType"> text/html;charset=UTF-8 </param> </result> </action> (2)提高freemarker的性能 在freemarker.properties中设置: template_update_delay=60000 避免每次请求都重新载入模版,即充分利用cached的模版 (3)尽量使用freemarker本身的提供的tag,使用S2 tags 的标签会在性能上有所损失 (4)freemarker的标签种类: ${..}:FreeMarker will replace it in the output with the actual value of the thing in the curly brackets. They are called interpolation s. # ,代表是FTL tags( FreeMarker Template Language tags) ,hey are instructions to FreeMarker and will not be printed to the output <#if ...></#if> <#list totalList as elementObject>...</#list> @ ,代表用户自定义的标签 <#-- --> 注释标签,注意不是<!-- --> (5)一些特殊的指令: r代表原样输出:${r"C:foobar"} <#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list> ?引出内置指令 String处理指令: html:特殊的html字符将会被转义,比如"<",处理后的结果是&lt; cap_first 、lower_case 、upper_case trim :除去字符串前后的空格 sequences处理指令 size :返回sequences的大小 numbers处理指令 int:number的整数部分,(e.g. -1.9?int is -1) (6)对于null,或者miss value,freemarker会报错 ?exists:旧版本的用法 !:default value operator,语法结构为: unsafe_expr !default_expr,比如 ${mouse!"No mouse."} 当mouse不存 在时,返回default value; (product.color)!"red" 这种方式,能够处理product或者color为miss value的情况; 而product.color!"red"将只处理color为miss value的情况 ??: Missing value test operator ,测试是否为missing value unsafe_expr ?? :product.color??将只测试color是否为null (unsafe_expr )??:(product.color)??将测试product和color是否存在null Ftl代 码 1. <#if mouse??> 2. Mouse found 3. <#else> 4. No mouse found 5. </#if> converted by Web2PDFConvert.com
  • 8. 6. Creating mouse... 7. <#assign mouse = "Jerry"> 8. <#if mouse??> 9. Mouse found 10. 11. <#else> 12. No mouse found 13. </#if> (7)模版 值 插入方式 (interpolation) 模版 通用方式 ( Universal interpolations ): ${expression } 对于字符串:只是简单输出 对于数值,会自动根据local确定格式,称为human audience,否则称为computer audience,可以"?c", 比如, <a href="/shop/details?id=${product.id ?c }">Details...</a>,因此这里的id是给浏览器使用的,不需要进行格式化,注意?c只对数值 有效 对于日期,会使用默认的日期格式转换,因此需要事先设置好默认的转换格式,包括date_format , time_format ,atetime_format 对于布尔值,不能输出,会报错并停止模版的执行,比如${a = 2} 会出错,但是可以 string built-in来进行转换 数 值处 理,具体参考: Built-ins for numbers http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number 数值处理的例子: <#setting number_format="currency"/> <#assign answer=42/> ${answer} ${answer?string} <#-- the same as ${answer} --> ${answer?string.number} ${answer?string.currency} ${answer?string.percent} 除了使用内置的formate,可以使用任何用Java decimal number format syntax 书写的formate,比如 <#setting number_format="0.###E0"/> <#setting number_format="0"/> <#setting number_format="#"/> ${1234} ${12345?string("0.####E0")} 更加方便的格式: <#setting locale="en_US"> US people writes: ${12345678?string(",##0.00")} <#setting locale="hu"> Hungarian people writes: ${12345678?string(",##0.00")} 日期处理,参考Built-ins for dates http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date 日期处理的例子: ${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} 注意: converted by Web2PDFConvert.com
  • 9. 由于java语言中的Date类型的不足,freemarker不能根据Date变量判断出变量包含的部分(日期、时间还是全部),在这种情 况下,freemarker 不能正确显示出${lastUpdated?string.short} 或者 simply ${lastUpdated},因此,可以通过?date, ?time and ?datetime built-ins 来帮助freemarker来进行判断,比如${lastUpdated?datetime?string.short} 除了使用内置的日期转换格式外,可以自己指定日期的格式,使用的是Java date format syntax,比如: ${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')'")} 数 值专 用方式 ( Numerical interpolations ):#{expression } or #{expression ; format },这是数值专用的输出方式,但是 最好使用通用方式的string built-in或者number_format 来完成转换,Numerical interpolations 方式将会被停用 (8)创建自定义模版 Ftl代 码 1. <#macro greet> 2. <font size="+2">Hello Joe!</font> 3. </#macro> <#assign user="zhangsan"/> 字符串连接 ${"Hello ${user}!"} 与 ${"Hello " + user + "!"} 相同 结果:Hello zhangsan 获取字符 ${user[0]} ${user[4]} 结果:z g 序列的连接和访问 <#assign nums=["1" , "2"] + ["3" , "4"] /> ${nums[0]} 结果是 1 内置函数 html 使用实体引用替换字符串中所有HTML字符,例如,使用&amp; 替换& lower_case 将字符串转化成小写 substring index_of 例如”abcdc"?index_of("bc") 将返回1 seq_contains 序列中是否包含指定值 ${nums?seq_contains("1")?string("yes","no")} seq_index_of 第一个出现的索引 ${nums?seq_index_of("1")} 结果0 sort_by 用于散列 240多个jQuery插件 | 创建oracle数据库连接(database link)的两 ... 09:59 浏览 (3931) 评论 (1) 分类: Freemarker 相关推荐 评论 1 楼 zhousheng193 2010-08-13 引用 值得学习,非常感谢! 发 表 评论 B I U Quote C ode List Img URL Flash Table 表情 图标 字体颜色: 标准 字体大小: 标准 对齐: 标准 提示:选择您需要装饰的文字, 按上列按钮即可添加上相应的标签 converted by Web2PDFConvert.com
  • 10. 您还没有登录,请登录后发表评论(快捷键 Alt+S / Ctrl+Enter) 提交 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。若作者同意转载,必须以超链接形式标明文章原始出处和作者。 © 2003-2010 JavaEye.com. All rights reserved. 上海炯耐计算机软件有限公司 [ 沪ICP备05023328号 ] converted by Web2PDFConvert.com