简体   繁体   中英

Velocity: How do I define a global variable

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?

您可以将该变量添加到VelocityContext中,然后每个人都可以使用,并将其用作全局变量。

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 .

如果使用VelocityTools创建上下文,则可以轻松设置和管理全局数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM