list转string去掉中括号(list<string>转list<map>)

list转string去掉中括号(list<string>转list<map>)sdfsf html 返回安全的 html 输出 替换掉 html 代码 xml 安全输出 var xml substring 的用法 lt assign user hello jeen gt user 0 user 4 user 1 4 输出 ho ello 类似 String split 的用法 abc def ghi split

大家好,我是讯享网,很高兴认识大家。

sdfsf”?html

\({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?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"."> 打印输出: 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”%>

<body>    

    <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>

讯享网

模板ftl页面

讯享网 <@html.errors/>
 <@html.form action="/query">      

Keyword: <@html.text property=“keyword”/>

Exclude: <@html.text property=“exclude”/>

 <@html.submit value="Send"/>    
 </@html.form>

如何初始化共享变量 1. 初始化全局共享数据模型 freemark在web上使用的时候对共享数据的初始化支持的不够,不能在配置初始化的时候实现,而必须通过ftl文件来初始化全局变量。这是不能满主需求的,我们需要在servlet init的时候留出一个接口来初始化系统的共享数据 具体到和webwork整合,因为本身webwork提供了整合servlet,如果要增加全局共享变量,可以通过修改com.opensymphony.webwork.views.freemarker.FreemarkerServlet来实现,我们可以在这个servlet初始化的时候来初始化全局共享变量 与webwork整合配置 配置web.xml

讯享网<servlet-name>freemarker</servlet-name> <servlet-class>com.opensymphony.webwork.views.freemarker.FreemarkerServlet</servlet-class> <init-param> <param-name>TemplatePath</param-name> 

/ <!—模板载入文件夹,这里相对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>

template_update_delay <!—模板更新时间,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-name>freemarker</servlet-name> <url-pattern>*.ftl</url-pattern> 

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 = “5”> \({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转义,转换’,“,换行等特殊字符 模板:

输出:

2.内置的默认值处理:default 用途: 用于处理默认值 模本: User: \({userLogin.name?default("Anonymous")} <td>\){(employee.department.manager.name)?default(” “)} 输出: User: Anonymous 注,可以对整个对象树加上(),再用内置处理器这种方便的做法,偶也是最近刚学会的,以前一直用很傻的方法做…..

  1. Sequence内置的计数器: xxx_index 用途:显示序号 模板: <#list employees as e> \({e_index}. \){e.name} </#list> 输出:
  2. Readonly
  3. Robbin
  4. Sequence内置的分段器: chunk 用途:某些比较BT的排版需求 模板: <#assign seq = [‘a’, ‘b’, ‘c’, ’d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’]> <#list seq?chunk(4) as row>
    • <#list row as cell>${cell} </#list>

</#list> <#list seq?chunk(4, ‘-’) as row> <#list row as cell>${cell} </#list> </#list> 输出:

  • a
  • b
  • c
  • d

    • e
    • f
    • g
    • h

      • i
      • j

        a b c d e f g h i j - - 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} 注意重复的键对应的值取最后的一个

        ★运算 ${52?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

        22222#

        struts2.0 标签+ftl标签 FreeMarker中文API手册(完整) http://blog.csdn.net/junjun16818/article/details/

        三目: ${true?string(‘5’,‘7’)}

        ${line.class.simpleName} <#if line.class.simpleName==“ViewLine”>你好</#if>

        list里面是object数组 <#if (areaList?exists)>

        讯享网<#list areaList as line> 

        \({line[1]}:\){line[0]}

        </#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> </#list> </#if>

        1.注释: 包含在<#–和–>

        2.注意: 由于Freemarker会将>解释成FTL标记的结束字符,所以对于>和>=可以使用括号来避免这种情况,例如

        <#if (x > y)>

        3.<#local y = “test”> 定义局部变量

        4.<#import “/lib/my_test.ftl” as my> 导入模板文件 指定名字空间 my

        1. if指令

        <#if animals.python.price < animals.elephant.price>

        Pythons are cheaper than elephants today.

        <#else>

        Pythons are not cheaper than elephants today.

        </#if>


        讯享网

        1. list指令以及列表序号

        <#list animals as being>

        第${being_index+1}个<#–默认是0开始–>

        \({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>

        </#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

        1. cap_first 将字符串中的第一个单词的首字母变为大写。

        ${‘str’?cap_first}à结果为Str

        1. uncap_first将字符串中的第一个单词的首字母变为小写。

        ${‘Str’?cap_first}à结果为str

        1. capitalize将字符串中的所有单词的首字母变为大写

        ${‘str’? capitalize}à结果为STR

        1. 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

        注意:如果指定的字符串格式不正确将引发错误。

        1. ends_with 判断某个字符串是否由某个子串结尾,返回布尔值。

        ${“string”?ends_with(“ing”)?string} 返回结果为true

        注意:布尔值必须转换为字符串才能输出

        1. html 用于将字符串中的<、>、&和“替换为对应得<>“:&
        2. 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

        1. lower_case将字符串转为小写

        ${“STRING”?lower_case}à结果为string

        11.upper_case将字符串转为大写

        ${“string”?upper_case}à结果为STRING

        1. contains 判断字符中是否包含某个子串。返回布尔值

        ${“string”?contains(“ing”)?string} à结果为true

        注意:布尔值必须转换为字符串才能输出

        1. 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

        1. trim 删除字符串首尾空格 ${“ String ”?trim} à结果为String

        四、 操作数字

        1. c 用于将数字转换为字符串

        ${123?c} à结果为123

        1. 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>

        <#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

        语法

        讯享网 ... <#break> 

        <#case refValue2>

         ... <#break> 
        讯享网 ... <#break> 

        <#default>

         ... 

        </#switch>

        备注:该指令官方不推荐使用了,可以用if, else, elseif 指令代替。

        list, break

        讯享网 ... 

        </#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

        实例:
        <#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> Hello Joe! </#macro> 使用的方式为: <@greet></@greet> //同xml可以简写成<@greet/>

        宏的参数定义,类似js,在宏名后 带参数进行传递定义 <#macro greet person color> ${person} </#macro>

        调用带参数时,注意使用类似XML的属性格式进行传递,不需要关心顺序问题 <@greet person=“Fred” color=“black”/>

        参数默认值定义,如果没有,就必须要求传递完整的参数列表 <#macro greet person color=“black”> Hello ${person}! </#macro>

        使用xml的嵌套内容进行传递宏调用,关键标签 <#nested> <#macro border>

        讯享网<#nested> 

        </#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>

        Copyright © \({date} Julia Smith. All rights reserved. <br>Email: \){mail}

        </#macro> <#assign mail = “”>

        lib/my_inc.ftl文件 <#import “/lib/my_test.ftl” as my> <#assign mail=“”> <@my.copyright date=“1999-2002”/> \({my.mail} \){mail} 输出结果将不会出现冲突

        对于库中的变量修改,使用in关键字 <#assign mail=“” 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:foobar”}

        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:设置格式化输出日期时

         </p> </dd> </dl> 
小讯
上一篇 2025-04-29 18:31
下一篇 2025-05-23 11:10

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/190541.html