tags:

views:

127

answers:

2

Is it possible to get a list of variables inside the template and fill them in using the list? I would like my users to create their templates that means i won't know before hand what variables will be available?

EDIT:

In my template users will decide what gets printed. Such as

$users $latest

but from my application i won't know which variables are used in the template. I would like to get a list such as [users latest] that includes all the variables in the template so that i can fill them in according to the user spec.

A: 

I don't think there is an easy way of doing that without overriding some of velocity classes.

Here is some options how I would do it:

  1. Add all possible variables (I am assuming there is a predefined set of them). If it is performance heavy look into caching.
  2. Ask users which data they need before rendering template (if it is a one time thing just a form, if those variables don't change often write them into db).
  3. Ask users to provide list of variables they need in some specific format inside the template for easy parsing before rendering a template, like: <!--%%__VARS__%%users,latest%%__VARS__%%-->
  4. Use regexp to search the template file and look for $var instances, which could be tricky.
serg
A: 

You may be able to gather a list by rendering the template and using a ReferenceInsertionEventHandler that builds a list. The trouble with that though is if the templates have things like:

#if( $foo ) $bar #else $woogie #end

Your event handler would only ever see either $bar or $woogie, not both.

This unsupported (and perhaps outdated) class may help:

https://svn.apache.org/repos/asf/velocity/engine/trunk/experimental/templatetool/

Nathan Bubna