开发者

Processing multiple nested templates using freemarker(or any other template engine)

开发者 https://www.devze.com 2023-04-07 11:02 出处:网络
I am开发者_StackOverflow中文版 trying to use FreeMarker to write a complex web page using servlets.

I am开发者_StackOverflow中文版 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.


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 a Writer, and you write whatever you want into that. Thus, of course, you can include other servlets, or do whatever is doable in Java. (Nested Template.process calls are supported.) See the source code of freemarker.ext.servlet.IncludePage as an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号