关于freemarker模板的建议,想要创建一个主模板

时间:2010-07-19 14:42:10

标签: java spring spring-mvc freemarker

我想创建一个每个其他视图页面都会继承的主模板。

因此主模板将具有:

HEADER
--CONTENT--
FOOTER
  1. 标题可选择显示(如果用户已登录),用户名和其他用户对象属性。

  2. --CONTENT--是占位符,其他“继承”视图页面会将其内容注入其中。

  3. 所以我的问题是,这可能与freemarker有关吗?如果有,任何指导?

    如何将用户对象从控制器操作传递到标头?理想情况下,对象将在每个视图页面以外的其他地方传递(以避免在每个视图页面上维护此代码)。

4 个答案:

答案 0 :(得分:3)

是的,这是可能的。在我们的应用程序中,用户对象之类的东西存在于会话范围内,但这可能是freemarker有权访问的任何范围:

<#if Session.the_user?? && Session.the_user.loggedIn>
    <#-- header code -->
</#if> 

您可以省略Session.,Freemarker将搜索给定变量名称的各种范围。

要注入内容,请在主模板中您希望视图页面放置其内容的位置包含此内容:

<#nested>

然后,视图页面声明如何使用主模板:

<#import "/WEB-INF/ftl/path/to/template/master.ftl" as com>
<@com.template>
    View page content
</@com.template>

答案 1 :(得分:1)

我制作了Freemarker模板继承 - https://github.com/kwon37xi/freemarker-template-inheritance 我想这就是你想要的。它在freemarker 2.3.19上进行了测试。

答案 2 :(得分:0)

我实现了这样的东西:

base.ftl

<#macro page_head>
  <title>Page title!</title>
</#macro>

<#macro page_body></#macro>

<#macro display_page>
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <@page_head/>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <@page_body/>
  </body>
  </html>
</#macro>

然后index.ftl将继承样板模板:

<#include "base.ftl">
<#macro page_head>
  <title>Welcome studs!</title>
</#macro>

<#macro page_body>
    <h1> Welcome user</h1>
</#macro>
<@display_page/>

此站点对于上面的代码参考很有帮助 https://nickfun.github.io/posts/2014/freemarker-template-inheritance.html

答案 3 :(得分:0)

在较新的 Freemarker 版本中,<#nested> 元素非常有用:

base.ftl:

<#macro layout>
    <html>
    <body>
    <p>OptaPlanner AI</p>
    <#nested>
    </body>
    </html>
</#macro>

baseWithDownloadButton.ftl:

<#import "base.ftl" as base>

<@base.layout>
    ${content.body}<#-- Only applicable for jbake -->
    <p>Download button</p>
</@base.layout>
相关问题