lordlamer lordlamer - 2 months ago 25
Java Question

freemarker with spring - how to bind global data to a template?

I want to create a small project with spring mvc and freemarker.

I have created a small template and a layout:

Template:

<#import "layout/defaultLayout.ftl" as layout>
<@layout.myLayout>
<div><h1>Hello Dude</h1></div>
</@layout.myLayout>


Layout:

<#macro myLayout>
<html>
<body>
<!-- menu -->

<!-- content -->
<#nested/>
</body>
</html>
</#macro>


My question now:
How could I create a dynamic value(perhaps bean data)?
I do not want to add the data in each controller action.
What is a good solution to put such data to a complete layout that is not specific to a controller action?

Answer

I found my own solution. I need to use a ControllerAdvice annotation and a ModelAttribute annotation like this:

@ControllerAdvice
public class LayoutMenu {
    @ModelAttribute("foo")
    public String initMenu() {
        return "Hello Bar";
    }
}

This solves my problem.