Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1068197
  • 博文数量: 282
  • 博客积分: 10865
  • 博客等级: 上将
  • 技术积分: 2480
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-12 12:35
文章存档

2017年(1)

2016年(3)

2015年(10)

2014年(12)

2013年(5)

2012年(10)

2011年(29)

2010年(3)

2008年(13)

2007年(92)

2006年(104)

我的朋友

分类: Java

2007-04-22 18:34:49

Freemarker是一个出色的模板引擎技术。但是为了判断需要,经常在ftl文件中嵌套太多的if,也正是OOer的大忌。在Java中,我们一般通过策略模式来避免这个问题,那么在Freemarker中我们应该什么做呢?
1.首先:写一段测试代码:
    public void testMacro() {
        // 模板文件
        Template templateFile = TemplateUtils.getTemplate("test/template",
                "macro.ftl");
        Map root = new HashMap();
        root.put("testMethod", new TestMethod());
        root.put("type", "password");
        BufferedWriter out = null;
        // 模板处理完的文件,存为Java类的形式
        File destFile = new File("test/dest/destmacro.txt");
        try {
            // 输出
            out = new BufferedWriter(new FileWriter(destFile));
            templateFile.process(root, out);
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
2.写一个macro.ftl文件:
  ${testMethod("${type}", "hello")}
3.写一个TestMethod类:
 public class TestMethod implements TemplateMethodModel {
     private static Map typeMap = new HashMap();
     static {
  typeMap.put("password", new PassWordParser());
  typeMap.put("calendar", new CalendarParser());
     }
     /**
      * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
      */
     public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 2) {
      throw new TemplateModelException("Wrong arguments");
  }
  String type = (String) arguments.get(0);
  String name = (String) arguments.get(1);
  return ((ITypeParser) typeMap.get(type)).parser(name);
     }
 }
4.写二个解析构造类:
 public class PassWordParser implements ITypeParser {
     public String parser(String name) {
  return "";
     }
 }
 public class CalendarParser implements ITypeParser {
     public String parser(String name) {
  return "";
     }
 }

这样生成的目标文件destmacro.txt的内容就是这样的:

就避免了大量的if语句,原先用if语句的ftl是这样的:
<#if type == "password">
    
<#elseif type == "calendar">
    
<#else>
    

阅读(3502) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~