Search code examples
htmlthymeleafstring-interpolation

How can I interpolate a string from varaible in a bootstrap label-success with thymeleaf


I have the following html content:

<span th:if="${game.isWon()}" class="label label-success">
        YOU WIN! Game Score: ${game.getGameScore()}.</span>

I can't figure out how to interpolate game.getGameScore() and the raw string keeps getting rendered. I'm using thymeleaf with Spring Boot. Any help would be much appreciated.


Solution

  • If you want to use attributes directly in text (and not in HTML attributes) you have to use inlining which has its own syntax. (Note that inlining is on by default in Thymeleaf 3, but you may have to use the attribute th:inline="text" on earlier versions). For example:

    <span th:if="${game.won}" class="label label-success">
        YOU WIN! Game Score: [[${game.gameScore}]].
    </span>
    

    The traditional way to do this, is just to add some extra tags:

    <span th:if="${game.won}" class="label label-success">
        YOU WIN! Game Score: <span th:text="${game.gameScore}" />.
    </span>