Share data via thymeleaf fragment

孤街醉人 提交于 2021-01-03 06:28:44

问题


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:


  1. You can create an interceptor and add model attribute on the postHandle method (which allows you access to the ModelAndView object. The interceptor will have to be on all the controllers that have this fragment.

  2. You can add the relevant model attributes to the session and access them via ${session.attribute}.

  3. Use the @ControllerAdvice annotation in combination with @ModelAttribute to add a model attribute to all controllers.



来源:https://stackoverflow.com/questions/55750955/share-data-via-thymeleaf-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!