Search code examples
velocity

Apache Velocity : Verify if all substitutions are made


Can someone let me know how I can verify a velocity context against a template? Basically, I want to throw some error if all variables are not substituted in the velocity template.

For example, let's say I have a velocity template, card.vm

  card {
    type: CREDIT
    company: VISA
    name: "${firstName} ${lastName}"
  }

The substitution is done like below

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
   
Template t = velocityEngine.getTemplate("card.vm");
    
VelocityContext context = new VelocityContext();
context.put("firstName", "tuk");
StringWriter writer = new StringWriter();
t.merge( context, writer );

In this case, I want to throw some error specifying that lastName is not replaced in template.

Does velocity provide anything for this?

  • Velocity Version - 1.7

Solution

  • This has been answered in velocity mailing list

    No, but it would be easy to do. Instead of using the basic VelocityContext, wrap it in a custom one, something like this:

    public class WarningVelocityContext
         extends VelocityContext
    {
         public Object get(String key) {
             Object o = super.get(key);
    
             if(null == o) {
                 throw new IllegalStateException("Key {" + key + "} has not
    been set");
             }
         }
    }
    

    Then in your code, wrap the context right before merging:

    t.merge(new WarningVelocityContext(context), writer);

    Note that this will throw exceptions for anything that's not found for any reason. If you try something like:

    $someObject.method()

    And "someObject" is null, then you'll get an error. It may be difficult to tell the difference between the things you "care about" and the things you do not. If you have a simple use-case, then probably this will work.