使用 freemarker(或任何其他模板引擎)处理多个嵌套模板
我正在尝试使用 FreeMarker 来使用 servlet 编写复杂的网页。
该页面有 3 个基本组件:顶部的导航栏、左侧的广告栏和中间的主要内容部分。我有一个单独的 servlet 来绘制其中的每一个。每个 servlet 只是生成一个 html5 部分,并且可能会也可能不会使用 freemarker。
当然,上述所有内容都位于使用 freemarker 模板化的主网页内。
问题是这样的。 主页的模板看起来像这样(为了简单起见,有很多条纹):
<html>
<body>
<!--lots of stuff in between-->
<section-nav> <!--this should be filled by output of NavServlet.respond -->
<!--lots of stuff in between-->
<section-content> <!-- this comes from arbitrary servlet for actual content -->
<section-advertise> <!--this should be filled by output of AdvertiseServlet -->
</body>
</html
How to handle the 上述结构使用 FreeMarker? 如果我为主页执行 template.process() ,它将同时写入 html 开始和结束标记,但我想要的是让其他 servlet(导航、广告等)有机会在 html 结束标记之前生成内容。
如果我们不能使用 FreeMarker 来实现此目的,我也可以使用其他模板解决方案。
I am trying to use FreeMarker to write a complex web page using servlets.
The page has 3 basic components: the nav-bar on top, the advertising-bar on left and the main content section in middle. I have a separate servlet to draw each one of these. Each servlet just churns out a html5 section, and may or may not use freemarker.
All of the above are ofcourse inside the main web page which is templated with freemarker.
The problem is this.
The template of main page looks something like this(striped lots for simplicity):
<html>
<body>
<!--lots of stuff in between-->
<section-nav> <!--this should be filled by output of NavServlet.respond -->
<!--lots of stuff in between-->
<section-content> <!-- this comes from arbitrary servlet for actual content -->
<section-advertise> <!--this should be filled by output of AdvertiseServlet -->
</body>
</html
How to handle the above structure using FreeMarker?
If I do template.process() for the main page it would write both the html start and end tag, but what I want is give other servlets(nav, advertise etc.) a chance to produce content before the html end tag.
If we cant use FreeMarker for this, I could use others templating solutions as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该实现
TemplateDirectiveModel
以在 Java 中创建自定义指令(而不是在 FTL 中,即使用#macro
)。当从模板(例如<@my.embed source="thisAndThatServlet" />
)调用时,它将收到一个Writer
,你可以写任何你想要的内容进入那个。因此,当然,您可以包含其他 servlet,或者执行 Java 中可以执行的任何操作。 (支持嵌套Template.process
调用。)请参阅freemarker.ext.servlet.IncludePage
的源代码作为示例。You should implement
TemplateDirectiveModel
to create a custom directive in Java (as opposed to in FTL, i.e., with#macro
). When called from a template (something like<@my.embed source="thisAndThatServlet" />
), it will receive aWriter
, and you write whatever you want into that. Thus, of course, you can include other servlets, or do whatever is doable in Java. (NestedTemplate.process
calls are supported.) See the source code offreemarker.ext.servlet.IncludePage
as an example.