自动HTML编码NVelocity输出(EventCartridge& ReferenceInsert)

我想尝试让NVelocity自动对我的MonoRail应用程序中的某些字符串进行HTML编码。 我查看了NVelocity源代码并找到了
EventCartridge
,这似乎是一个可以插件来改变各种行为的类。 特别是这个类有一个
ReferenceInsert
方法,似乎完全符合我的要求。它基本上在引用值(例如$ foobar)输出之前被调用,并允许您修改结果。 我无法解决的是如何配置NVelocity / MonoRail NVelocity视图引擎来使用我的实现? Velocity文档建议velocity.properties可以包含用于添加这样的特定事件处理程序的条目,但我找不到查找此配置的NVelocity源代码中的任何位置。 任何帮助非常感谢! 编辑:一个简单的测试,显示这个工作(概念证明,所以不是生产代码!)
private VelocityEngine _velocityEngine;
private VelocityContext _velocityContext;

[SetUp]
public void Setup()
{
    _velocityEngine = new VelocityEngine();
    _velocityEngine.Init();

    // creates the context...
    _velocityContext = new VelocityContext();

    // attach a new event cartridge
    _velocityContext.AttachEventCartridge(new EventCartridge());

    // add our custom handler to the ReferenceInsertion event
    _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> &lt;p&gt;This &quot;should&quot; be &#39;encoded&#39;&lt;/p&gt;", 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("&", "&amp;")
        .Replace("<", "&lt;")
        .Replace(">", "&gt;")
        .Replace(""", "&quot;")
        .Replace("'", "&#39;"); // &apos; does not work in IE
}
    
已邀请:
尝试将新的EventCartridge附加到VelocityContext。请参阅这些测试作为参考。 现在你已经确认这种方法有效,继承
Castle.MonoRail.Framework.Views.NVelocity.NVelocityEngine
,覆盖
BeforeMerge
并在那里设置
EventCartridge
和事件。然后配置MonoRail以使用此自定义视图引擎。     

要回复问题请先登录注册