Home > Net >  Get a Thymeleaf template fragment in Java
Get a Thymeleaf template fragment in Java

Time:05-21

I have a template :

<div th:fragment="subject">
    [[${var1}]] -  blabla
</div>
<div th:fragment="body">
titi
</div>

In Java :

I want to retrieve only the subject fragment and put it in a variable.

String subject =  templateEngine.process(template.getPath() " :: subject", context);

but I got the error :

java.io.FileNotFoundException: ClassLoader resource "mail/templates/mail_depot.html :: subject" could not be resolved

I can successfully call:

String subject =  templateEngine.process(template.getPath(), context);

but when I add " :: subject" to only retrieve the subject fragment I got an error.

CodePudding user response:

The TemplateEngine has different versions of the process() method. The one you need is:

public final String process​(String template, Set<String> templateSelectors, IContext context)

This method takes a set of strings, where each string can be the name of a fragment.

For example:

Set<String> selectors = new HashSet<>();
selectors.add("subject");

String subject =  templateEngine.process(template.getPath(), selectors, context);

In your case, this will return a string containing:

<div>
    ??? -  blabla
</div>

But with the ??? replaced by whatever value [[${var1}]] resolves to.


See the TemplateEngine JavaDoc for more details.

  • Related