我有一个包含#parse其他模板的模板。 问题是我不知道我试图解析alwais的文件存在。
我已经在velocity-tools-2.0.jar中输入了IncludeTool类,我已添加为变量,但仍然必须测试它失败。 有人能告诉我如何将IncludeTool添加到我的模板中吗?
private VelocityContext transmitParameters(params prm){
VelocityContext c = new VelocityContext();
//transmit parameters one by one
c.put("program_name", prm.getProgram_name());
c.put("date", new DateTool());
c.put("incl", new IncludeTool());
return c;
}
public generate(params prm) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, constants.TEMPLATE_PATH);
ve.init();
context = new VelocityContext(transmitParameters(p));
writer = new StringWriter();
t.merge(context, writer);
}
和模板
#if($incl.exists("templates/$record.name/file.vm"))
#parse("$record.name/file.vm")
#end
谢谢。
答案 0 :(得分:0)
我觉得奇怪的是路径上的差异。其中一个包含模板/,另一个没有。我倾向于尝试
#if($incl.exists("$record.name/file.vm"))
#parse("$record.name/file.vm")
#end
如果这不起作用,有一些事情需要尝试
答案 1 :(得分:0)
我创建了一个带有exists函数的新类(正如David Vonka建议的那样)
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;
public class existTemplate {
private VelocityEngine engine;
public existTemplate(VelocityEngine e) {
engine =new VelocityEngine();
engine = e;
}
public boolean exists(String name)
{
try
{
// checks for both templates and static content
return engine.resourceExists(name);
}
// make sure about this...
catch (ResourceNotFoundException rnfe)
{
return false;
}
catch (NullPointerException rnfe)
{
return false;
}
}
}
然后在发送参数时使用它
VelocityEngine ve = new VelocityEngine();
ve.init();
incl = new existTemplate(ve);
VelocityContext c = new VelocityContext();
c.put("date", new DateTool());
c.put("incl", incl);
内部tempalte用作:
#if($incl.exists("$record.name/file.vm"))
#parse("$record.name/file.vm")
#end