Freemarker模板文件返回字符串
程序员文章站
2022-07-14 09:53:12
...
首先,先创建一个ftl文件:
之后,创建一个java应用程序类:
由于有用到自定义方法,因此在建个方法类:
运行后,得到所要的结果
<div style="width:100%;font-size:12px;">Hello ${name}(${getUserAge(name)})</div>
之后,创建一个java应用程序类:
package freemarker;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
*
* @Desc 获取FTL文件生成的字符串,以供调用
* @author xujp1
* @version Revision: 1.00 Date: May 9, 2012
*/
public class GenerateStringFromFtl
{
private static Configuration conf = null;
public static void main(String args[])
{
conf = new Configuration();
try
{
conf.setDirectoryForTemplateLoading(new File("WebRoot/WEB-INF/template"));
}
catch (IOException e)
{
e.printStackTrace();
}
conf.setObjectWrapper(new DefaultObjectWrapper());
conf.setLocale(Locale.CHINA);
conf.setSharedVariable("getUserAge", new GetUserAge());//自定义方法供调用
conf.setDefaultEncoding("utf-8");
conf.setClassicCompatible(true);//处理空值为空字符串
String tempReturn = "";
Map<String, Object> root = new HashMap<String, Object>();
String name = "xujp1";
root.put("name", name);
try
{
tempReturn = generateHtmlFromFtl(root, "hellouser.ftl");
}
catch (IOException e)
{
e.printStackTrace();
}
catch (TemplateException e)
{
e.printStackTrace();
}
System.out.println(tempReturn);
}
public static String generateHtmlFromFtl(Object root, String tempPath) throws IOException, TemplateException
{
Template temp = conf.getTemplate(tempPath);
Writer out = new StringWriter(2048);
temp.process(root, out);
return out.toString();
}
}
由于有用到自定义方法,因此在建个方法类:
package freemarker;
import java.util.List;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;
/**
*
* @Desc freemarker中使用的方法,根据传入的参数返回相应的值
* @author xujp1
* @version Revision: 1.00 Date: May 9, 2012
*/
public class GetUserAge implements TemplateMethodModel
{
/* (non-Javadoc)
* @see freemarker.template.TemplateMethodModel#exec(java.util.List)
*/
@SuppressWarnings("unchecked")
@Override
public Object exec(List args) throws TemplateModelException
{
if(args.size() != 1)
{
throw new TemplateModelException("Wrong arguments!");
}
int age = 0;
if("xujp1".equalsIgnoreCase((String)args.get(0)))
age = 25;
else
age = 24;
return new SimpleScalar(String.valueOf(age));
}
}
运行后,得到所要的结果
上一篇: Freemarker 字符串函数
下一篇: python装饰器原理