1.宏学习
定义:
<#macro prom pid>
<#if pid=="1">
。。。。。。。。。。。。。。
</#if>
</#macro>
其它页面中引入:
<#import "/products/choice_size.html" as productSize>
在页面中使用:
<@productSize.prom pid="${product.templateId!}"/>
2.时间转换
<#if r[0]??>${r[0].createTime?string("yyyy-MM-dd HH:mm:ss")!}</#if>
3.freemarker操作
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class Test {
public static void main1(String[] args) throws Exception {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("bin")); //设置读取模板文件的目录
Template t = cfg.getTemplate("a.html"); //读取文件名为Test.ftl的模板
Map root = new HashMap(); //存储数据
Writer out = new OutputStreamWriter(new FileOutputStream("Test.html"), "UTF-8"); //输出流
t.process(root,out);
System.out.println("Create successfully!");
}
public static void main2(String[] args)throws Exception{//freemarker获取生成后的字符串
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("bin")); //设置读取模板文件的目录
Template t = cfg.getTemplate("a.html");
Map root = new HashMap(); //存储数据
Writer writer = new StringWriter();
t.process(root,writer);
writer.flush();
writer.close();
System.out.println(writer.toString());
}
public static void main3(String[] args)throws Exception{//根据字符串生成一个经过处理后的字符串
Configuration cfg = new Configuration();
StringTemplateLoader loader = new StringTemplateLoader();
cfg.setTemplateLoader(loader);
loader.putTemplate("default", "wwwwwwwwwwwwwwwwwwwww");
Map root = new HashMap(); //存储数据
Template template = cfg.getTemplate("default");
Writer writer = new StringWriter();
template.process(root, writer);
System.out.println(writer.toString());
}
}
html页面
<#macro greet person,website>
Hello ${person}! Your Website is ${website}.
</#macro>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<@greet person="Sfeve" website="http://sfeve.iteye.com"/>
</body>
</html>
编码的问题:
解决方法:
A.Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setDefaultEncoding("UTF-8");
Template template = freemarkerCfg.getTemplate(templateFileName);
B. template.setEncoding("UTF-8");
C. Writer out = new OutputStreamWriter(new FileOutputStream("Test.html"),"UTF-8");