我一直在使用 FreeMarker现在有一段时间了,但是有一个明显的功能要么丢失了,要么我就是想不通(我希望是后者!)。如果您向 cfg.getTemplate() 传递一个绝对路径,它就不起作用。我知道你可以指定一个模板目录,但我不能这样做,我的用例可以处理任何目录中的文件。有什么方法可以设置 FreeMarker 以任何用户期望的方式呈现绝对路径?
最佳答案
我不得不使用绝对路径,因为模板是在 Ant 脚本中发生的,模板在文件系统上,并通过 Ant 文件集发现。我想这些是相当独特的要求......
无论如何,对于后代(只要 SO 已启动),这里有一个有效的解决方案:
public class TemplateAbsolutePathLoader implements TemplateLoader {
public Object findTemplateSource(String name) throws IOException {
File source = new File(name);
return source.isFile() ? source : null;
}
public long getLastModified(Object templateSource) {
return ((File) templateSource).lastModified();
}
public Reader getReader(Object templateSource, String encoding)
throws IOException {
if (!(templateSource instanceof File)) {
throw new IllegalArgumentException("templateSource is a: " + templateSource.getClass().getName());
}
return new InputStreamReader(new FileInputStream((File) templateSource), encoding);
}
public void closeTemplateSource(Object templateSource) throws IOException {
// Do nothing.
}
}
初始化是:
public String generate(File template) {
Configuration cfg = new Configuration();
cfg.setTemplateLoader(new TemplateAbsolutePathLoader());
Template tpl = cfg.getTemplate(template.getAbsolutePath());
// ...
}
关于java - 在 FreeMarker 中使用绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1208220/