Freemarker中的指令、数据类型、命名空间、内建函数

来源:互联网 发布:魔方数据是什么 编辑:程序博客网 时间:2024/04/28 04:49

主要要记得各种指令的写法

1.if指令

test.ftl

Hello ${user}你的成绩是 <#if score gte 90> 优秀! <#elseif score gte 60> 良好! <#else> 不及格!</#if> 
测试类

import java.io.File;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.HashMap;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class Test {public static void main(String[] args) throws IOException, TemplateException {Configuration cfg = new Configuration();// 加载目录cfg.setDirectoryForTemplateLoading(new File("templates"));Map root = new HashMap();// 数据模型是树状模型root.put("user", "张巍");root.put("score", 90);Template tp = cfg.getTemplate("test.ftl");Writer out = new OutputStreamWriter(System.out);tp.process(root, out);out.flush();out.close();}}

2.list指令

test.ftl

Hello ${user}你的成绩可能是 <#list arr as score>${score}</#list>

测试类

import java.io.File;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class Test {public static void main(String[] args) throws IOException, TemplateException {Configuration cfg = new Configuration();// 加载目录cfg.setDirectoryForTemplateLoading(new File("templates"));Map root = new HashMap();// 数据模型是树状模型 root.put("user", "张巍");ArrayList arr = new ArrayList();arr.add("优秀");arr.add("良好");arr.add("不及格");root.put("arr", arr);Template tp = cfg.getTemplate("test.ftl");Writer out = new OutputStreamWriter(System.out);tp.process(root, out);out.flush();out.close();}}

3.include指令

创建一个includetest.ftl文件

test.ftl

Hello ${user}你的成绩可能是 <#list arr as score>${score}</#list><#include "inclusetest.ftl">

测试类不变


4.macro指令(宏指令、自定义指令)

test.ftl

Hello ${user}你的成绩可能是 <#list arr as score>${score}</#list><#include "inclusetest.ftl"><#macro m1 a b c>${a} ${b} ${c}</#macro><@m1 a="我" b="爱" c="你" />

我们在这里定义了一个宏 m1 参数为 a b c

调用时给他们一一传参就行了

测试类不变


5.nested (嵌入指令)

Hello ${user}你的成绩可能是 <#list arr as score>${score}</#list><#include "inclusetest.ftl"><#macro m1 a b c>${a} ${b} ${c}</#macro><@m1 a="我" b="爱" c="你" /><#macro m2><#nested></#macro> <@m2>你也爱我</@m2>

测试类不变

6.assign(定义变量的指令)

<#assign name="zhangwei" />



数据类型的话,注意下时间的取值

时间变

${date1?string(yyyy-MM-dd HH:mm:ss)}

可以这样格式化时间

比较运算符

gt 大于  gte 大于等于 lt 小于 lte 小于等于


还有命名空间 ,其实命名空间就一个作用,区分不同ftl文件的重名

内建函数

${htm?html] 对htm变量使用内建函数html

常用的内建函数

html 进行html编码

cap_first 首字母大写

lower_case 字符串小写

upper_case 字符串大写


0 0