Ionut Ovidiu Georgescu Ionut Ovidiu Georgescu -4 years ago 53
Java Question

Apache velocity IncludeTool - conditional include

I have a template that will include with #parse other templates.
The problem is that I don't know that the file I'm trying to parse alwais exists.

I've foud the IncludeTool class in the velocity-tools-2.0.jar, I've added as a variable but still when he must test it fails.
Can someone tell me how to add the IncludeTool to my template?

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);
}


And the template

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


Thank you.

Answer Source

I've created a new class with the exists function (as David Vonka suggested)

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;
        }
    }

}

and then used it when sending the parameters

VelocityEngine ve = new VelocityEngine();
ve.init();
incl = new existTemplate(ve);

VelocityContext c = new VelocityContext();
c.put("date", new DateTool());
c.put("incl", incl);

inside tempalte is used like :

#if($incl.exists("$record.name/file.vm"))
#parse("$record.name/file.vm")
#end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download