I wanted to try getting NVelocity to automatically encode HTML strings in my MonoRail application.
I looked at the source code of NVelocity and found EventCartridgewhich seems to be a class that you can plug in to modify different types of behavior.
In particular, this class has a method ReferenceInsertthat seems to do exactly what I want. It is basically called just before the link value (e.g. $ foobar) gets output, and allows you to modify the results.
What I cannot decide is how I configure the NVelocity / MonoRail NVelocity viewer to use my implementation?
Velocity docs show that speed.properties may contain entries for adding specific event handlers like this, but I cannot find anywhere in the source code of NVelocity that is looking for this configuration.
Any help is much appreciated!
Edit: A simple test that shows this work (proof of concept, not production code!)
private VelocityEngine _velocityEngine;
private VelocityContext _velocityContext;
[SetUp]
public void Setup()
{
_velocityEngine = new VelocityEngine();
_velocityEngine.Init();
_velocityContext = new VelocityContext();
_velocityContext.AttachEventCartridge(new EventCartridge());
_velocityContext.EventCartridge.ReferenceInsertion += EventCartridge_ReferenceInsertion;
}
[Test]
public void EncodeReference()
{
_velocityContext.Put("thisShouldBeEncoded", "<p>This \"should\" be 'encoded'</p>");
var writer = new StringWriter();
var result = _velocityEngine.Evaluate(_velocityContext, writer, "HtmlEncodingEventCartridgeTestFixture.EncodeReference", @"<p>This ""shouldn't"" be encoded.</p> $thisShouldBeEncoded");
Assert.IsTrue(result, "Evaluation returned failure");
Assert.AreEqual(@"<p>This ""shouldn't"" be encoded.</p> <p>This "should" be 'encoded'</p>", writer.ToString());
}
private static void EventCartridge_ReferenceInsertion(object sender, ReferenceInsertionEventArgs e)
{
var originalString = e.OriginalValue as string;
if (originalString == null) return;
e.NewValue = HtmlEncode(originalString);
}
private static string HtmlEncode(string value)
{
return value
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'");
}
source
share