私は、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> <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
}