我想尝试使Nvelocity在我的Monorail应用程序中自动编码某些字符串。

我浏览了nvelocity源代码,发现 EventCartridge, ,这似乎是您可以插入各种行为的类。

特别是这个课程 ReferenceInsert 似乎完全可以完成我想要的方法。基本上,它在参考值(例如$ foobar)获取输出之前就被调用,并允许您修改结果。

我无法解决的是如何配置Nvelocity/Monorail Nvelocity View Engine使用我的实现?

速度文档 建议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 和事件。然后配置单轨铁路以使用此自定义视图引擎。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top