日期:2014-05-17 浏览次数:21136 次
在freemarker中可以使用 #include 命令引入其他的文件。
但是今天自己在写代码的时候遇到一个问题,比如我的代码目录结构是这样的:

我在freemarker下面的一个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.Map;
import freemarker.template.Configuration;
import 
freemarker.template.Template;
import 
freemarker.template.TemplateException;
public class TestInclude {
    private Configuration cfg = null;
    public Configuration getCfg() {
        return cfg;
    }
    public void init() throws IOException {
        cfg = new 
Configuration();
        cfg.setDirectoryForTemplateLoading(new 
File("bin/freemarker"));
    }
    public static void main(String args[]) throws IOException, 
TemplateException {
        TestInclude obj = new TestInclude();
        
obj.init();
        Map root = new HashMap();
        Template t = 
obj.getCfg().getTemplate("TestInclude.ftl");
        Writer out = new 
StringWriter();
        t.process(root, out);
        
System.out.println(out.toString());
    }
}
?
然后在TestInclude.ftl 中引入如下:
<html>
<head> 
 
<title>Testpage</title>
</head> 
<body> 
 <h1>Testpage</h1>  
<p>Blahblah... 
<#include 
"/free/test.ftl"> 
</body> 
</html>
结果就抛异常了,找不到free/test.ftl
郁闷。于是改成<#include "bin/free/test.ftl"> 喔,还是不行
继续,改成<#include "../bin/free/test.ftl"> ,这样也不行呀?
?
最后的解决方法如下:
?
public class TestInclude {
    private Configuration cfg = null;
    public Configuration getCfg() {
        return cfg;
    }
    public void init() throws IOException {
        cfg = new 
Configuration();
  
cfg.setDirectoryForTemplateLoading(new File("bin"));
    
}
    public static void main(String args[]) throws IOException, 
TemplateException {
        TestInclude obj = new TestInclude();
        
obj.init();
        Map root = new HashMap();
Template t = 
obj.getCfg().getTemplate("/freemarker/TestInclude.ftl");
        
Writer out = new StringWriter();
        t.process(root, out);
        
System.out.println(out.toString());
    }
}
然后在TestInclude.ftl中如下写:
<#include "/free/test.ftl">
是不是可以这样理解,就算是include中的路径,和TestInclude。ftl 一样,都是相对于 cfg.setDirectoryForTemplateLoading(new File("bin")); 这个目录的吧。。。。