自动编码Nvelocity输出(EventCartridge&ReferenceInsert)的HTML
-
30-09-2019 - |
题
我想尝试使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> <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("'", "'"); // ' does not work in IE
}
解决方案
尝试将新的EventCartridge附加到VelocityContext。看 这些测试 作为参考。
现在您已经确认了这种方法有效,从而继承了 Castle.MonoRail.Framework.Views.NVelocity.NVelocityEngine
, ,覆盖 BeforeMerge
并设置 EventCartridge
和事件。然后配置单轨铁路以使用此自定义视图引擎。
不隶属于 StackOverflow