2

I have my messages.properties like this:

tablas.menu.paises=Pa\u00EDses
tablas.menu.regiones=Regiones
tablas.menu.anhos=A\u00F1os
tablas.menu.universidades=Universidades
tablas.menu.usuarios=Usuarios

In the .html I have a menu showing each item with th:each:

<li class="nav-item" th:each="menu : ${menus}">
  <a th:text="#{tablas.menu.${menu.nombre}}"></a>
</li>

For each "menu in ${menus}", menu.nombre has the values paises, regiones, anhos... But thymeleaf doesn't recognise the model variable inside the #{}, and this it is giving me in the view the error when it doesn't find the message:

??tablas.menu.${menu.nombre}_es_ES??

Configuration is ok, if I change the call for #{tablas.menu.regiones} I get 'regiones' and so. Is there any way to call a message from messages.properties dynamically using a model variable like this?

Thanks.

3
  • 1
    Try the Thymeleaf preprocessor. So, for example: _${menu.nombre}_. Commented Apr 10, 2020 at 18:24
  • 1
    Damn thank you so much, I didn't know that feature and it works. th:text="#{tablas.menu.__${menu.nombre}__}" is working perfect. Commented Apr 10, 2020 at 18:37
  • 1
    And thank you for correcting my typo - double underscores are needed, not singles. Commented Apr 10, 2020 at 19:11

1 Answer 1

2

You can use the #messages utility object for this:

<a th:text="${#messages.msg('tablas.menu.' + menu.nombre)}" />

Or you can create the string using literal substitution:

<a th:text="#{|tablas.menu.${menu.nombre}|}" />

I would recommend using preprocessing only as a last resort, as bad values can cause runtime errors. (Although they do work for this.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.