Withtaker
Withtaker

Reputation: 1904

Thymeleaf: Building variable names dynamically

I am trying to build the name of a var dynamically by concatenating the value of a variable and adding some string afterwards, as I add these variable in runtime. Something like the following should work but it does not.

th:text="${__#{myClass.getA().getB()}+'-result'__}"

Is this even possible to do? I dont know the name of the variable, I can only construct it like this unfortunately.

Upvotes: 5

Views: 3559

Answers (1)

Ioan M
Ioan M

Reputation: 1207

Yes, that is possible, Thymeleaf supports expression preprocessing:

Let's start with some examples: The message(i18n) expressions should be referenced using the # character. So let's suppose you have the message.key in your translation file. To reference it in Thymeleaf you will have to use

th:text="#{message.key}"

In your scenario your key name is generated dynamically based on a variable so for preprocessing it in thymeleaf you need to use two underscores __

Let's suppose in your context you have a model variable called myModelVariable with a method messagePrefix(). Our example becomes:

th:text="#{__${myModelVariable.messagePrefix()}__}"

This means the myModelVariable.messagePrefix() will be processed first and the result will be used as the key name which will be then resolved to a nice user friendly message.

And if you also want to add a static part at the end of it will look like this:

th:text="#{__${myModelVariable.messagePrefix()}__}+'*'"

Even the key can contain a static part so this is also accepted:

th:text="#{__${myModelVariable.messagePrefix()}__.staticsuffix}+'*'"

More info you can find in the section 2.7 here: https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

Upvotes: 5

Related Questions