Search code examples
templatesvelocity

How can I see all variables available inside a Velocity Template?


Is it possible to display all variables available inside a Velocity Template?

Let's say 1 developer pass 2 values to template: $headline and $body. Another developer has to deal with those 2 variables. How would he know names of those variables?

Right now we use 3 solutions:

  • we simply say what variables are present on templates
  • we agreed with all developers that all data we pass to template should be included into 1 map ($data)
  • developer that pass variables to templates has to update template as well and describe all the fields available on it.

I'm looking for way to do this correctly. Right now I'm not really satisfied with all approaches, but 2-nd looks like most preferable.


Solution

  • The short answer is:

    $context.keys
    

    The variables and "tools" are accessed by the templates via the velocity "context". If the context tool is available, you can request the list of variables via $context.keys. If not, you need to add the tool ContextTool to the context. How this is done depends on your application.

    Although it's technically possible to list all keys in the context, I'm not sure it's also good practice in the situation you describe.