Yanis Yakuza
Yanis Yakuza

Reputation: 131

Get a Thymeleaf template fragment in Java

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.

Upvotes: 3

Views: 929

Answers (1)

andrewJames
andrewJames

Reputation: 22042

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.


Update

Follow-up related question: If you want to directly access the content of the fragment, excluding the enclosing HTML tags, you can use the following:

<th:block th:fragment="subject">
    foo
</th:block>
<div th:fragment="body">
    bar
</div>

The Thymeleaf <th:block> tag removes itself.

If you have nested tags inside your fragment, those will not be removed if you use <th:block>.

Otherwise, use an HTML parser such as Jsoup:

Jsoup.parse(yourHtmlString).text()

Upvotes: 5

Related Questions