在 NVelocity 模板中如何测试属性是否存在
我正在构建一个简单的 NVelocity 模板,但我不知道如何测试变量是否存在 - 在这个示例中,我想测试上下文是否包含名为 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();
I'm building a simple NVelocity template but I can't figure out how to test for the existence of a variable -- In this example I want to test if the context contains a property callwed User.
I know I can implement the same functionality as a hacked foreach loop but I was wondering if there's a better way.
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上下文本身不是上下文的一部分,因此
$context
不起作用。您可以这样检查是否存在:The context itself is not a part of the context, so
$context
doesn't work. You can check for presence like this: