Search code examples
spring-bootthymeleaf

Thymeleaf dymamic text tag


In the controller, I am adding a bunch of attributes to the model like test_1, test_2, test_3. In thymeleaf, I want to use those attributes in a text tag like th:text="${test_1}". However, the text is within a fragment, so I want to dynamically set the number in the tag. I feel like the key is using th:with, or preprocessing, but I haven't found something that works. Here's what I tried.

th:with="i='test_' +${number}" th:text="${i}"

th:text="'test_' + ${number}"

th:text="${'test_'+__${number}__}"

All of these simply have test_1 (or whatever number is specified) as the output, instead of pulling that value from the model.


Solution

  • You can use the following:

    <div th:text="${__${'test_' + number}__}"></div>
    

    This uses something very similar to your 3rd example, but it places the entire string concatenation inside a preprocessor.

    Test data:

    • number is set to 2 in your Java/Spring model.
    • test_2 is set to "bar" in your Java/Spring model.

    Explanation:

    1. First, use the preprocessor syntax to build the string you want - where that string matches a variable in the model:

      __${'test_' + number}__

    The above Thymeleaf expression evaluates to the string test_2.

    1. Because this was a pre-processed variable, it effectively becomes the following, when it is wrapped inside a ${...}:

      ${test_2}

    The above evaluates to the string "bar" - which is what you want.


    "the text is within a fragment": I am not sure what the relevance of that is. It should not matter. If I have misunderstood, maybe you can edit the question to clarify.