Search code examples
spring-mvctemplate-enginethymeleaf

Process Thymeleaf attributes multiple times


I would like to be able to store HTML with Thymeleaf attributes as Strings in a database. I am able to store HTML without Thymeleaf attributes already:

Method in controller class

// this method would actually get String from database first
@ModelAttribute("someCode")
public String populateSomeCode() {
    return "This is <h1>some code</h1>";
}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
...
  <body>
    <div th:utext="${someCode}">HTML will go here</div>
  </body>
</html>

This would produce the desired result of displaying an H1 saying "This is some code".

I am wondering if it is possible to include Thymeleaf attributes in the String and then have those attributes processed. If I changed the String to be:

"This is <h1 th:text=\"'another String'\">some code</h1>"

I would like the result to be an H1 saying "This is another String", but currently it would still say "This is some code". Is there a way to do this?


Solution

  • Have you tried to use Thymeleaf __${expression}__ preprocessor feature?

    Like this:

    "This is __<h1 th:text=\"'another String'\"> some code</h1>__"