簡體   English   中英

自動HTML編碼NVelocity輸出(EventCartridge和ReferenceInsert)

[英]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> &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以使用此自定義視圖引擎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM