Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share data via thymeleaf fragment

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?

like image 608
jukenduit Avatar asked Nov 26 '25 00:11

jukenduit


1 Answers

  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.

like image 118
Metroids Avatar answered Nov 27 '25 14:11

Metroids



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!