Home > Software design >  use thymeleaf fragment variable to select i18n phrase
use thymeleaf fragment variable to select i18n phrase

Time:02-21

I am using Thymeleaf and have localisation files set up and working fine, but for help I want to show help for the relevant page, so I am passing the page as a fragment variable.

I know I could use a th:switch/case and go through a bunch of options, but surely there is a quicker way?

So far any variation on this:

<p th:text="#{help.${page}}"></p>

only returns

??help.${page}_en??

instead of retrieving help.page3=foo bar, and displaying foo bar

I have already tried without second curly braces, and also adding in square braces, but so far no luck. Is there a nice shorthand that works? Or am I stuck with setting up a switch?

Yes I realise I could have written the switch 5 times by this point......

CodePudding user response:

What you need is expression preprocessing. You can do it as follows:

<p th:text="${__#{help.${page}}__}"></p>

CodePudding user response:

You need expression preprocessing on just the variable in question:

<p th:text="#{help.__${page}__}"></p>
  • Related