Velocity: How do I define a global variable

北城余情 提交于 2019-12-10 10:48:34

问题


I tried adding a bunch of #set($x=abc) statements in the VM_global_library.vm file, but these variables aren't available in my VM templates.

I'd like to set a single global variable for things like the base path to images and such. Is this possible?


回答1:


Your VM_global_library.vm should only contain Velocity macros, I suspect any variables declared outside of a macro are just ignored.

You could create a separate .vm file that holds all of your globals, and then make sure you #parse it in every template where you need them (or you could write some code to automatically parse it). I've previously extended the VelocityLayoutServlet for example to do something similar: merge my "global-variables.vm" first to add them to the Context, and then carry on and render the view.

If your globals are just simple strings it would probably be more efficient to put them in a properties file and have your code push them directly into the VelocityContext.




回答2:


You can add that variable to the VelocityContext and then it will be available to everyone and will act as a Global Variable.




回答3:


It's easy to set up and manage global data if you create your Context with VelocityTools.



来源:https://stackoverflow.com/questions/5013078/velocity-how-do-i-define-a-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!