tags:

views:

27

answers:

1

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();
A: 

The context itself is not a part of the context, so $context doesn't work. You can check for presence like this:

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