Through the macro features provided by FreeMarker, we can easily manage some of the commonly used template code.

Add FreeMarker Property

Add FreeMarker property into application.properties:

1
spring.freemarker.settings.auto_import=common.ftl as common

Create Templates

Common Template

  • Right click resources/templates directory: New > File
  • Fill in: common.ftl
  • Click “OK” button
img

Copy and paste the following content into common.ftl:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<#macro header>
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Dong Chen">

    <title>Shop</title>
</head>
</#macro>

<#macro footer>
   <footer>
        <span>Copyright © 2019. All Rights Reserved.</span>
    </footer>
</#macro>

Index Template

  • Right click resources/templates directory: New > File
  • Fill in: index.ftl
  • Click “OK” button
img

Copy and paste the following content into index.ftl:

1
2
3
4
5
6
7
<html lang="en-NZ">
    <@common.header/>
    <body>
        Shop Home Page
    </body>
    <@common.footer/>
</html>

Add Method into FreeMarkderControll Controller

Copy and paste the following content into FreeMarkerController.java:

1
2
3
4
    @RequestMapping("home")
    public String home() {
        return "index";
    }

Verify

Run the App

1
2
// Short Cut for "Run the Program"
Alt + Shift + F10
img

Choose the correspondent option and press enter.

View Home Page in the Browser

1
http://localhost:8080/home
img

From now on, we can use the header and footer macros from the common template in any template file.

References macro, nested, return

Buy me a coffeeBuy me a coffee