在NVelocity模板中,您如何测试属性的存在

时间:2010-06-25 10:05:27

标签: nvelocity

我正在构建一个简单的NVelocity模板,但我无法弄清楚如何测试变量的存在 - 在这个例子中,我想测试上下文是否包含一个属性callwed User。

我知道我可以实现与黑客foreach循环相同的功能,但我想知道是否有更好的方法。

Velocity.Init();

VelocityContext context = new VelocityContext();
context.Put("from", "somewhere");
context.Put("to", "someone");
context.Put("subject", "Welcome to NVelocity");


String s = @"From: $from To: $to Subject: 
#if($context.ContainsKey('User'))
    We Have a User
#else
    No User Found
#end";

var sw = new System.IO.StringWriter();
Velocity.Evaluate(context, sw, "", s);

string merged = sw.ToString();

1 个答案:

答案 0 :(得分:0)

上下文本身不是上下文的一部分,因此$context不起作用。你可以检查这样的存在:

#if ($user)
  we have a user
#else
  no user found
#end