title: Cleanest way to display sanitized HTML with Thymeleaf?
body: <p>I have some data in my database where we allow a subset of HTML to be entered to display later. Out of paranoia / not trusting older versions of the code, I would like to run this through something like Jsoup's <a href="http://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer" rel="nofollow">Jsoup.clean()</a> before displaying it, to prevent Cross-Site Scripting (XSS) issues.</p>
  
  <p>Additionally, I'd like to replace <code>"\n"</code> with <code>"&lt;br/&gt;"</code>, so that people who typed in more free-form text to these fields get something reasonable looking later.</p>
  
  <p>In my JSPs, I had a custom taglib written to handle this, which I used like this:</p>
  
  <pre><code>&lt;util:whitelistHtml value="${some.thing}" convertNewlines="true"/&gt;
  </code></pre>
  
  <p>What would be the cleanest way to recreate this behavior in Thymeleaf? I see a few options:</p>
  
  <ul>
  <li>A parameterized fragment, making use of Spring expressions to call out to Jsoup, like <code>th:utext="${T(org.jsoup.Jsoup).clean(some.thing.replaceAll('\n', '&lt;br/&gt;'), T(org.jsoup.safety.Whitelist).basic())}"</code>.</li>
  <li>A custom dialect, where I write a new <code>foo:cleanHtml="${some.thing}"</code> attribute handler, possibly extending <code>org.thymeleaf.standard.processor.attr.StandardUtextAttrProcessor</code> and <code>org.thymeleaf.standard.processor.attr.AbstractStandardUnescapedTextChildModifierAttrProcessor</code> to do most of the work.</li>
  <li>Some custom utility object I can use, like <code>th:utext="${#cleaners.cleanHtml(${some.thing}, true)}"</code></li>
  <li>Do this processing in my controller, and just pass an extra model attribute with the "clean" form of things, or perhaps have the controller overwrite the properties of the main model object directly, then just use <code>th:utext="${some.thing}"</code>.</li>
  </ul>
  
  <p>Which of the above would be most likely to keep working after Thymeleaf 3, and would also have the least risk of accidental XSS exposure, or would at least make the code easier to audit for that than JSP files are?</p>