0

I'm storing blog posts in mongodb. Posts can have new lines (stored as \n\r) and/or anchor tags.

{
    "header" : "Some header",
    "body" : "The first paragraph.\n\rThe second paragraph\n\r<a href=\"www.example.com\" title=\"Example\">Example text</a>",
    "languageCode" : "DE"
}

By doing this in my thymeleaf view I can display the new lines:

<p class="card-text" th:utext="${#strings.replace(#strings.escapeXml(blogEntry.blogPost.body),'&#10;','&lt;br&gt;')}"></p>

However the anchor tags are displaying as plain text.

How to format the anchor tag that comes from the controller as an actual link to another site?

Sebastian M
  • 471
  • 1
  • 4
  • 20

1 Answers1

1

Remove the #strings.escapeXml(...) function.

Notes:

Using th:text means that any HTML in the related string will be escaped - i.e. a string such as "...<br>..." will be treated as a literal string. Using th:utext means that the string will remain unescaped - so any HTML tags in a string such as "...<br>..." will be treated as HTML.

However, by also using #strings.escapeXml(...), you are reversing the effect of th:utext by escaping the string being processed. In this case, this is not what you want.

Be aware of the potential risks associated with using th:utext. For example, you may want to escape user-provided (i.e. untrusted) input in some other way before saving it in your data store.

andrewJames
  • 19,570
  • 8
  • 19
  • 51