Search code examples
asp.netextension-methodsnvelocity

NVelocity extension method ASP.NET webform


I was wondering if it's possible to use an extension method with asp.net webforms and nvelocity. I would like to set some defaults if the string value is null or empty.

Example of .vm file:

    Example of my email body...

    Billable Status: $billableStatus.Evaluate()

    rest of my email body...

Attempted extension method:

public static class Helper
{
    public static string Evaluate(this string value)
    {
        if (String.IsNullOrEmpty(value))
            return "Not Provided";
        else
            return value;
    }
}

Or is there an alternative to what I'm tryting to accomplish?


Solution

  • I don't think NVelocity can resolve extension methods with C#/VB.NET syntax sugar. What I do is register an instance of a helper in the velocity context:

    var context = VelocityContext();
    context.Put("helper", new Helper());
    context.Put("billableStatus", "something");
    ...
    

    and then in your template:

    $helper.Evaluate($billableStatus)
    

    You have to make your helper non-static for this to work, of course.