2017-05-25 56 views
0

我有一個模板將包含#parse其他模板。 問題是,我不知道我想解析alwais的文件存在。Apache速度IncludeTool - 有條件包含

我已經在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

我創建了一個新類的存在功能(如大衛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 
0

我絕對看起來很奇怪的是路徑的差異。其中一個包含模板/,另一個不包含。我會傾向於嘗試

#if($incl.exists("$record.name/file.vm")) 
#parse("$record.name/file.vm") 
#end 

如果還是不行,有一些事情要嘗試

  1. 你能不存在的試運行#parse(「fakerecord/file.vm」),如果該文件存在於fakerecord文件夾中?
  2. 將$ incl.getClass()。getCanonicalName()放入您的模板中。它打印什麼?
+0

1.如果文件存在,解析工作正常。但我不想創建空模板,以使#parse函數可以工作 2.它打印出來:org.apache.velocity.tools.view.IncludeTool –

+0

引起:java.lang.NullPointerException在 org.apache。 velocity.tools.view.IncludeTool.exists(IncludeTool.java:192)
內IncludeTool.java '公佈爾存在(字符串名稱){ 嘗試模板和靜態內容 回報 {// 檢查engine.resourceExists(名稱); } //確認這個... catch(ResourceNotFoundException rnfe) { return false; } }' –

+0

這裏是引擎的初始化: 'VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,constants.TEMPLATE_PATH); ve.init();' –