Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent thymeleaf from replacing special characters in HTML attribute values?

I'am using Thymeleaf in combination with a js micro-templating routine, which result in special characters in attribute values. When running Thymeleaf on

<a style="display:<%= x ? 'block' : 'none' %>;">

it creates

<a style="display:&lt;%= x ? &#39;block&#39; : &#39;none&#39; %&gt;;">

while I would expect to get exactly the same I put into the processor. How do I use special characters in HTML attribute values? Many thanks!

like image 337
brainfrozen Avatar asked Feb 14 '13 14:02

brainfrozen


Video Answer


2 Answers

Try to play with

th:utext="#{unescaped text}"> 

See Thymeleaf doc Unescaped Text

like image 106
Grigory Kislin Avatar answered Sep 22 '22 11:09

Grigory Kislin


There is some variants to review:

  • use LEGACYHTML5 option in templateResolver as mentioned above
  • override template method in Underscore.js

I prefer second approach. Place this code in your initialization script:

var original = _.template;
_.template = function(content) {
    // fix operators escaped by Thymeleaf HTML5 validator
    content = content.replace(/&#39;/g, "'");
    content = content.replace(/&lt;/g, "<");
    content = content.replace(/&gt;/g, ">");
    return original.call(this, content);
};
like image 20
yuliskov Avatar answered Sep 18 '22 11:09

yuliskov