速度:如何定义全局变量 [英] Velocity: How do I define a global variable
问题描述
我尝试在VM_global_library.vm文件中添加一堆 #set($ x = abc)
语句,但这些变量在我的VM模板中不可用。
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?
推荐答案
你的 VM_global_library.vm
应该只包含Velocity宏,我怀疑在宏之外声明的任何变量都会被忽略。
Your VM_global_library.vm
should only contain Velocity macros, I suspect any variables declared outside of a macro are just ignored.
你可以创建一个单独的 .vm
保存所有全局变量的文件,然后确保在需要它们的每个模板中 #parse
它(或者你可以编写一些代码来自动解析它)。我以前扩展了 VelocityLayoutServlet
,例如做类似的事情:首先合并我的 global-variables.vm
将它们添加到Context中,然后继续并呈现视图。
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.
如果你的全局变量只是简单的字符串,那么把它们放在属性中可能会更有效率文件并让你的代码直接将它们推送到 VelocityContext
。
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
.
这篇关于速度:如何定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!