Sunday, November 23, 2008

Stand-alone NVelocity with string templates

All I wanted was to render a string containing an NVelocity template with some parameters, but I kept getting an exception at runtime:

System.Exception: The specified class for Resourcemanager (NVelocity.Runtime.Resource.ResourceManagerImpl,NVelocity) does not exist.

I couldn't make it find NVelocity.dll in the GAC or through a relative path, but setting "Copy local" to "true" in NVelocity's properties (under "References" in the solution explorer) worked. This is equivalent to adding '<Private>True</Private>' to the assembly reference in the .csproj file.

So finally I can have this nice method:

/// 
/// Render a template with the Velocity engine
/// 
public static string Render(
  string template,
  IContext context,
  string templateNameForLogErrors)
{
  var velocity = new VelocityEngine(new ExtendedProperties());
  using (var writer = new StringWriter())
  {
    velocity.Evaluate(context, writer, templateNameForLogErrors, template);
    return writer.GetStringBuilder().ToString();
  }
}