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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With