3

I am trying to include the same bit of html into various pages. This template is a table that displays data from the database. I know Thymeleaf has fragments, but as far as I can tell I can't include a fragment with its own controller, which my template will need so it can retrieve the necessary data.

I have seen this question, but this template can be called multiple times on the same page and adding that many attributes to the Model does not seem like the correct solution(not to mention that the attribute names need to be unique).

Is there any way to include this template in Thymeleaf so it has its own controller separate from the page it is included too.

Community
  • 1
  • 1
Vinc
  • 695
  • 2
  • 10
  • 26

2 Answers2

2

I use an approach which I call "Service based rendering" :)

The idea behind is to leverage on the spring beans integration via @someService.

Instead of filling the Model you can call any bean with parameters coming from either the model, requestmapping, the template or fragment parameters or from wherever you can get them.

Little example:

<div th:each="someVar : ${@someService.getData(someParameter)}" th:text="${someVar}">Template Text</div>
Martin Frey
  • 10,025
  • 4
  • 25
  • 30
  • While this is possible (and may be the solution you're looking for), I think doing this is a bad idea in general. It is breaking the principles of MVC (by ignoring the model/controller) and will make your code harder to maintain & debug. – Metroids Feb 08 '17 at 19:32
  • 1
    @Metroids: I do not agree. I find it even easier to maintain as this way you can build "reusable components". I'm not talking business services, but rather component services. `Component` is an extensible annotation, so you can build like in my case a `UIService` living in the servletcontext. The model IS the resultset/entitylist and the fragment is the view. If you like i can edit the answer with an example. – Martin Frey Feb 14 '17 at 16:56
0

Nope, that just isn't possible using thymeleaf alone. One controller per page.

There are alternatives to simply adding all your attributes. You could put a collection on the model -- either a List or a Map -- and have your fragments index into that to get their data. (You can pass arguments to a fragment.)

That or a javascript solution.

Metroids
  • 18,999
  • 4
  • 41
  • 52