NVelocity: loading templates from embedded resources

http://www.codegeneration.net/logos/nvelocity.gif

In last week's tip on using the NVelocity template formatting engine, I described what to set to load a template from an absolute path.

Here's the magic necessary to get NVelocity to load a template from an embedded resource:

 VelocityEngine engine = new VelocityEngine();
ExtendedProperties properties = new ExtendedProperties();
properties.AddProperty("resource.loader", "assembly");
properties.AddProperty("assembly.resource.loader.class",
"NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity");
properties.AddProperty("assembly.resource.loader.assembly", "StencilFormatter");
engine.Init(properties);

3 Comments

  • Huh, didn't seem to work. I am assuming this code should allow you to create a template text file ("helloworld.vm" in my case) and embed it in an assembly, then load it from the assembly instead of the file system. I am also assuming "StencilFormatter" is the name of the assembly that contains the NVelocity template file. If these assumptions are correct, this example does not seem to work.

    I am using NVelocity v0.4.2.8580, and I get the following runtime exception (of type "Exception"):

    Problem initializing template loader: System.Collections.ArrayList
    Error is: at NVelocity.Runtime.Resource.Loader.ResourceLoaderFactory.getLoader(RuntimeServices rs, String loaderClassName)\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0

  • Hej Mike in your version of NVelocity the Loader you have to use is ResourceLoader and not AssemblyResourceLoader. That's why it's not working.

    Therefore this propery: properties.AddProperty("assembly.resource.loader.class",
    "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity");

    has to be
    properties.AddProperty("assembly.resource.loader.class",
    "NVelocity.Runtime.Resource.Loader.ResourceLoader, NVelocity");

  • Great!! Just what I was looking for.

Comments have been disabled for this content.