FreeMarker基础语法

来源:互联网 发布:python twisted adbapi 编辑:程序博客网 时间:2024/06/05 10:01

1、FreeMarker使用方法

@Testpublic void genFile() throws Exception {// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。Configuration configuration = new Configuration(Configuration.getVersion());// 第二步:设置模板文件所在的路径。configuration.setDirectoryForTemplateLoading(new File("D:/workspaces-itcast/term197/taotao-item-web/src/main/webapp/WEB-INF/ftl"));// 第三步:设置模板文件使用的字符集。一般就是utf-8.configuration.setDefaultEncoding("utf-8");// 第四步:加载一个模板,创建一个模板对象。Template template = configuration.getTemplate("hello.ftl");// 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。Map dataModel = new HashMap<>();//向数据集中添加数据dataModel.put("hello", "this is my first freemarker test.");// 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。Writer out = new FileWriter(new File("D:/temp/term197/out/hello.html"));// 第七步:调用模板对象的process方法输出文件。template.process(dataModel, out);// 第八步:关闭流。out.close();}

2、基础语法

2.1取pojo中的属性


      

2.2取集合中的数据

<#list studentList as student>

     ${student.id}/${studnet.name}

</#list>

循环使用格式:

<#list 要循环的数据as 循环后的数据>

</#list>




2.3取循环中的下标

<#list studentList as student>

       ${student_index}

</#list>


2.4判断

<#if student_index % 2 == 0>

<#else>

</#if>


2.5日期类型格式化

直接取值:${date}(date是属性名)如果传来的是一个Date型数据会报错

${date?date} 2016-9-13

${date?time} 17:53:55

${date?datetime} 2016-9-13 17:53:55


2.6Null值的处理

如果直接取一个不存在的值(值为null)时会报异常${aaa}。处理: ${aaa!”默认值”}或者${aaa! }代表空字符串


2.7Include标签




原创粉丝点击