假设您有一个标准模板,其中包含(已解析的)页眉、正文、页脚模板。
在正文模板中定义了像 $subject 这样的变量,并且您希望它也显示在标题模板中。
在一些其他模板语言中,例如 HTML::Mason(基于 perl),您将首先评估正文模板以获取 $subject 变量,但将其输出临时存储在变量中,以便您的最终输出可以以正确的顺序结束(标题, body, footer)
在速度中它看起来像
set ($body=#parse("body.vm"))
parse("header.vm")
${body}
parse("footer.vm")
但这并不'似乎不起作用,关于如何做到这一点有什么想法吗?
Say you have a standard template with included (parsed) header, body, footer templates.
In the body template a variable like $subject is defined and you want that also displayed in the header template.
In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)
In velocity it would look something like
set ($body=#parse("body.vm"))
parse("header.vm")
${body}
parse("footer.vm")
This however doesn't seem to work, any thoughts on how to do this?
发布评论
评论(3)
上述两种解决方案中的任何一种都可以。 VelocityLayoutServlet 解决方案需要一个名为 Velocity Tools 的额外软件包(也来自 Velocity)。 我本人偏爱这种方法(及其变体)。
第三种方法是将#parse 放在引号内:
在#set 内,双引号中的任何内容都会被评估。 单引号内的字符串按字面意思传递。
Either of the two solutions above would work. The VelocityLayoutServlet solution requires an extra package (also from Velocity) called Velocity Tools. I'm partial to this approach (and variants) myself.
A third method is simply to put the #parse within quotes:
Within a #set, anything in double quotes is evaluated. Strings within single quotes are passed in literally.
您可以使用 VelocityLayoutServlet 来完成此操作,它是 VelocityTools。
这允许您为应用程序定义一个布局 - 让我们称之为
application.vm
- 您可以在其中解析页眉、页脚等,并使用声明主体内容的放置位置>screen_content
声明,例如:VelocityLayoutServlet
将在渲染之前评估模板(以及变量),这允许您在正文中设置$subject
变量模板,例如:更详细的信息可以在 Velocity 文档中找到。
You can do this using VelocityLayoutServlet which is part of VelocityTools.
This allows you to define a layout for your application -- let's call it
application.vm
-- in which you can parse in headers, footers etc and declare where the main body content is placed using thescreen_content
declaration, e.g:VelocityLayoutServlet
will evalulate the templates (and, hence, variables) before rendering which allows you to set a$subject
variable in your body template, e.g:More detailed information can be found in the Velocity documentation.
如果我理解正确的话,您希望将一个名为
$subject
的 Velocity 变量插入到header.vm
和body.vm
模板中。 目前,该变量是在body.vm
模板中定义的,因此您无法在早期模板header.vm
中引用它。为什么不将 $subject 的定义抽象到它自己的模板片段中,称为 Globals.vm ,然后将其包含在顶级模板中。 所以你会有:
If I understand you correctly, you want to have a Velocity variable named
$subject
interpolated into theheader.vm
and thebody.vm
templates. Right now, the variable is defined in thebody.vm
template, so you cannot refer to it in the earlier templateheader.vm
.Why don't you abstract out the definition of $subject into its own template snippet, called
globals.vm
say, then include that in the top-level template. So you'd have: