Velocity:如何定义全局变量
我尝试在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将该变量添加到 VelocityContext,然后它将可供所有人使用并充当全局变量。
You can add that variable to the VelocityContext and then it will be available to everyone and will act as a Global Variable.
您的
VM_global_library.vm
应该只包含 Velocity 宏,我怀疑在宏之外声明的任何变量都会被忽略。您可以创建一个单独的
.vm
文件来保存所有全局变量,然后确保在每个需要它们的模板中#parse
它(或者您可以编写一些代码自动解析它)。例如,我之前扩展了VelocityLayoutServlet
来执行类似的操作:首先合并我的“global-variables.vm
”,将它们添加到上下文中,然后继续渲染视图。如果您的全局变量只是简单的字符串,那么将它们放入属性文件中并让您的代码将它们直接推送到
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 theVelocityLayoutServlet
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 创建上下文,则可以轻松设置和管理全局数据。
It's easy to set up and manage global data if you create your Context with VelocityTools.