问题
I have a thymeleaf fragment called nav which I include in all front-end pages, it goes like so:
<nav class="navbar navbar-expand-md navbar-dark bg-dark" th:fragment="nav">
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
How to get Java data here ?
</ul>
</div>
</nav>
But what I want to do now is get some data from the database and have that data available in this fragment, which in turn will appear on every page that includes this fragment.
If I want to pass data to a view regularly from a controller, I would use Model and model.addAttribute and return the appropriate view which would contain the relevant model data, but how can I pass data to this fragment?
回答1:
You can create an interceptor and add model attribute on the
postHandlemethod (which allows you access to theModelAndViewobject. The interceptor will have to be on all the controllers that have this fragment.You can add the relevant model attributes to the session and access them via
${session.attribute}.Use the
@ControllerAdviceannotation in combination with@ModelAttributeto add a model attribute to all controllers.
来源:https://stackoverflow.com/questions/55750955/share-data-via-thymeleaf-fragment