velocity: Loading templates using absolute path

Velocity is an awesome java templating engine, which I’m currently using in my web-app. As easy it is to follow the ‘hello world’ example, I just could not access the template using my java code. The problem here is that velocity is not designed to only cater to web applications. It assumes that the default directory in which your templates are posted is the one from which your application started. And no matter how hard you try, it just wouldn’t pick up the templates from an absolute path.
In my case, it was the jboss bin directory, which was hardly the place I’d place my velocity templates. A little bit of searching and researching, and I could figure out a solution to make it pick up templates using an absolute path.
Here’s the solution: You have to configure your velocity.properties file to include a bit of resource management.Include these few lines in your velocity.properties (and remove any other resource management bit, if you have it):

resource.loader = file

file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = .
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 2

The ‘file.resource.loader.path’ tells velocity to pick up templates from the absolute path. So, supposing your template’s path is /srv/test/Template.vm, you should try

Template template = velocityEngine.getTemplate("./srv/test/Template.vm");


One Response to “velocity: Loading templates using absolute path”

Leave a Reply