Thymeleaf th:text - Put a text without removing HTML structures

TemplatesSpring MvcThymeleaf

Templates Problem Overview


I'm new in thymeleaf and I try to create a template. My problem is this code:

CODE

<h1 th:text="${header.title}" >
   title
   <small th:text="${header.subtitle}" >Subtitle</small>
</h1>

I want to get this output:

<h1> TITLE <small> SUBTITLE</small> </h1>

But this is the real output:

<h1> TITLE </h1>

How can I do so it doesn't remove what is inside of "small"?

Templates Solutions


Solution 1 - Templates

I faced the same problem. The answer is th:inline='text'

This should solve your issue

<h1 th:inline="text" >
   [[${header.title}]]
   <small th:text="${header.subtitle}">Subtitle</small>
</h1>


or you can also use th:remove="tag"

<h1>
    <span th:text="${header.title}" th:remove="tag">title</span>
    <small th:text="${header.subtitle}" >Subtitle</small>
</h1>

Solution 2 - Templates

Regardless of the semantics of tags, the correct answer is this one:

<h1>
	<span th:text="${header.title}" th:remove="tag">title</span>
    <small th:text="${header.subtitle}" >Subtitle</small>
</h1>

In this way Thymeleaf removes de <span> tag and the results is what you expect:

<h1> 
    TITLE 
    <small>SUBTITLE</small> 
</h1>

Regards!

Solution 3 - Templates

in addition to @Faraj response, you can also use th:block like this

<h1>
   <th:block th:utext="${header.title}"/>
   <small th:text="${header.subtitle}" >Subtitle</small>
</h1>

Solution 4 - Templates

I'm not sure what you are trying, since the small tags in your h1 will not appear small. The Thymeleaf th:text tag will replace all the text in your h1 tag, that is the reason your output only shows "TITLE". You should place the <small> tags outside your h1 tag.

<h1 th:text="${header.title}">title</h1>

<small th:text="${header.subtitle}">Subtitle</small>

And I believe you are looking for this answer:

<h1>
   <span th:text="${header.title}" th:remove="tag">title</span>
   <small th:text="${header.subtitle}">Subtitle</small>
</h1>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnPortellaView Question on Stackoverflow
Solution 1 - TemplatesFaraj FarookView Answer on Stackoverflow
Solution 2 - TemplatesEmiliano SchianoView Answer on Stackoverflow
Solution 3 - TemplatesrvazquezglezView Answer on Stackoverflow
Solution 4 - TemplatesMichiel BijlsmaView Answer on Stackoverflow