Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC + Thymeleaf: adding variable to all templates' context

Tags:

How can I add a "global" variable such as username to be used all around my template context?

Currently I am setting these explicitly to each ModelAndView object in my TemplateController.

like image 243
Capuchin Avatar asked May 08 '15 10:05

Capuchin


People also ask

How do you add variables in Thymeleaf?

We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.

How do you pass parameters in Thymeleaf?

Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client to server like: https://example.com/query?q=Thymeleaf+Is+Great! In the above example if parameter q is not present, empty string will be displayed in the above paragraph otherwise the value of q will be shown.

How do you display value in Thymeleaf?

The return value of our controller's method should be the name of the desired Thymeleaf template. This name should correspond to the HTML file located in the src/resource/template directory. In our case, it'll be src/resource/template/articles-list. html.


1 Answers

Several ways to do this.

If you want to add a variable to all views served by a single controller, you can add a @ModelAttribute annotated method - see reference doc.

Note that you can also, using the same @ModelAttribute mechanism, address multiple Controllers at once. For that, you can implement that @ModelAttribute method in a class annotated with @ControllerAdvice - see reference doc.

like image 187
Brian Clozel Avatar answered Nov 03 '22 10:11

Brian Clozel