[英]Automatically HTML Encoding NVelocity Output (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> <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
和事件出現。 然后配置MonoRail以使用此自定義視圖引擎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.