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.
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:
http://svn.apache.org/viewvc/velocity/engine/branches/1.x/experimental/templatetool/
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:
- Add all possible variables (I am assuming there is a predefined set of them). If it is performance heavy look into caching.
- 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).
- 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__%%-->
- Use regexp to search the template file and look for $var instances, which could be tricky.
Here there are some discussion and ideas to resolve this. The preferred option is basically implement a walker for the generated AST of a template. Not trivial.
I found this one liner, (save it as a snippet) if you can't remember it.
## #foreach($key in $context.keys) <pre> $key</pre> #end
Hope it helps ...
Oh, remove the ##
as it is commented
精彩评论