I'm wondering how I can create a menu that is loaded dynamically (from the db) on every page.
I use spring boot + thymeleaf. no XML, just spring annotations.
I tried adding a controller with a method that returns a category object (which is used in the menu) annotated with (@ModelAttribute) but I couldn't use that attribute in my HTML pages. Here is my header:
<ul>
<li th:each="category : ${categories}" th:text="${category.name}">
</ul>
Now, this "ul" is loaded in every page since it's on the menu bar. I don't want to add the following code in every controller:
ModelAndView mav = new ModelAndView("index");
mav.addObject("categories", getCategories());
I need a way to achieve this without adding this code on every controller. just once.
Thanks
You can use @ControllerAdvice, adding "categories" attribute for each controller response. Since it's a spring component, you can autowire any of your existing services in it to retrieve categories.
@ControllerAdvice
public class CategoriesAdvice {
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("categories", getCategories());
}
}
See my github project with complete solution: project
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