现在的位置: 首页 > 综合 > 正文

从零学习freemarker(5)Include的使用

2013年10月04日 ⁄ 综合 ⁄ 共 1377字 ⁄ 字号 评论关闭
 http://www.java2000.net/p7861

Include的使用

代码

  1. package freemarker;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.OutputStreamWriter;
  5. import java.io.Writer;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import freemarker.template.Configuration;
  9. import freemarker.template.Template;
  10. public class TestInclude {
  11.   private Configuration cfg;
  12.   public Configuration getCfg() {
  13.     return cfg;
  14.   }
  15.   public void init() throws Exception {
  16.     cfg = new Configuration();
  17.     cfg.setDirectoryForTemplateLoading(new File("bin/freemaker"));
  18.   }
  19.   public static void main(String[] args) throws Exception {
  20.     TestInclude obj = new TestInclude();
  21.     obj.init();
  22.     Map root = new HashMap();
  23.     Template t = obj.getCfg().getTemplate("TestInclude.ftl");
  24.     Writer out = new OutputStreamWriter(new FileOutputStream("TestInclude.html"), "GBK");
  25.     t.process(root, out);
  26.     System.out.println("Successfull................");
  27.   }
  28. }

模板

  1. <html>
  2. <head>
  3.   <title>Test page</title>
  4. </head>
  5. <body>
  6.   <h1>Test page</h1>
  7.   <p>Blah blah...
  8. <#include "/TestInclude.copyright.html">
  9. </body>
  10. </html>  

TestInclude.copyright.html

  1. <hr>
  2. <i> Copyright (c) 2007-2008 <a href="http://www.java2000.net">JAVA世纪网</a><br>
  3. 版权所有. </i>

输出结果

  1. <html>
  2. <head>
  3.   <title>Test page</title>
  4. </head>
  5. <body>
  6.   <h1>Test page</h1>
  7.   <p>Blah blah...
  8. <hr>
  9. <i> Copyright (c) 2007-2008 <a href="http://www.java2000.net">JAVA世纪网</a><br>
  10. 版权所有. </i>
  11. </body>
  12. </html>  

抱歉!评论已关闭.