Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf fragment with own controller

I want to create a fragment with thymeleaf that has its own controller, so anytime I include the fragment, the controller is called and fills the necessary model attributes. To me this sounds like a basic request but I am new to thymeleaf and can't figure it out. So for example I have a fragment like this:

<div th:fragment="table">
  <tr th:each="prod : ${prods}">
    <td th:text="${prod.name}"/>
  </tr>
</div>

In addition to this fragment, I would have a controller that looks somewhat like this:

@RequestMapping(value="/getProducts")
public Model products(Model model){
    List<String> products = getProductList();
    model.addAttribute("prods", products)
    return model;
}

So how can I bind those two? I am using spring-boot and I did not change or edit any resolver. Thanks, Peer

like image 667
peer Avatar asked Jan 21 '26 09:01

peer


1 Answers

You can include another response into current page with

<th:block th:utext="${#servletContext.getRequestDispatcher('/path/to/fragment').include(#request,#response)}"/>

(method returns void, wrapped with utext to simply call it)

If this is frequent scenario, you can make it into a fragment accepting path parameter

<th:block th:fragment="include(url)">
    <th:block th:utext="${#servletContext.getRequestDispatcher(url).include(#request,#response)}"/>
</th:block>

and call with

<th:block th:include="~{::include(url='/path/to/fragment')}"/>
like image 179
aimozg Avatar answered Jan 25 '26 20:01

aimozg



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!