Search code examples
spring-mvcspring-bootthymeleaf

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


Solution

  • The idea von Spring MVC and a model is, that in the view only data a rendered. So it's a bad idea to call a service or a controller from any place in a template.

    You can solve this problem with a function addDataForTableFragment(Model model). This must be called from your controller which uses the template with the fragment. If you need the data at many method have a look a "ModelAttribute".