97

I'm using Thymeleaf to process html templates, I understood how to append inline strings from my controller, but now I want to append a fragment of HTML code into the page.

For example, lets stay that I have this in my Java application:

String n="<span><i class=\"icon-leaf\"></i>"+str+"</span> <a href=\"\"></a>\n";

final WebContext ctx = new WebContext(request, response, 
                                      servletContext, request.getLocale());
ctx.setVariable("n", n);

What do I need to write in the HTML page so that it would be replaced by the value of the n variable and be processed as HTML code instead of it being encoded as text?

Lii
  • 11,553
  • 8
  • 64
  • 88
Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71

3 Answers3

161

You can use th:utext attribute that stands for unescaped text (see documentation). Use this with caution and avoid user input in th:utext as it can cause security problems.

<div th:remove="tag" th:utext="${n}"></div>
Mahozad
  • 18,032
  • 13
  • 118
  • 133
michal.kreuzman
  • 12,170
  • 10
  • 58
  • 70
  • 4
    Updated link to v3 http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#unescaped-text – theINtoy Jun 14 '17 at 09:57
  • Does this work with Apache FOP as well while rendering a PDF. Because i don't see any change adding utext tag. – Dhiraj Gandhi Apr 10 '18 at 13:53
  • I tried this but it literally throws an error for every HTML tag I use saying it needs a closing tag, even when the closing tag is present. – Jackson Bray Oct 01 '18 at 14:57
  • 4
    Important thing to note: using utext makes you vulnerable to cross site scripting attacks. An attacker can store malicious html in your `n` variable that would get executed every time the page is rendered on your user's browser. See https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet – wi2ard Feb 05 '19 at 10:08
16

If you want short-hand syntax you can use following:

[(${variable})]

Escaped short-hand syntax is

[[${variable}]]

but if you change inner square brackets [ with regular ( ones HTML is not escaped.

Example within tags:

<div>
    [(${variable})]
</div>
michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
0

Staring with Thymeleaf 3.0 the html friendly tag would be:

<div class="mailbox-read-message" data-th-utext="*{body}">
metadevj
  • 21
  • 2
  • 2