3

私は、MonoRailアプリで特定の文字列を自動的にHTMLエンコードするようにNVelocityを取得してみたかったのです。

NVelocityのソースコードを調べたところEventCartridge、さまざまな動作を変更するためにプラグインできるクラスのようです。

特に、このクラスには、ReferenceInsert私が望んでいることを正確に実行しているように見えるメソッドがあります。基本的に、参照の値($ foobarなど)が出力される直前に呼び出され、結果を変更できます。

うまくいかないのは、実装を使用するようにNVelocity / MonoRailNVelocityビューエンジンを構成する方法です。

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
}
4

1 に答える 1

2

新しい EventCartridge を VelocityContext に接続してみてください。これらのテストを参考にしてください。

このアプローチが機能することを確認したので、 から継承し、そこで and イベントCastle.MonoRail.Framework.Views.NVelocity.NVelocityEngineをオーバーライドBeforeMergeして設定します。EventCartridge次に、このカスタム ビュー エンジンを使用するように MonoRail を構成します。

于 2010-12-03T18:43:03.103 に答える