Search code examples
thymeleafspring-thymeleaf

Thymeleaf: Check if message with dynamic key is null or empty


the key for the messages.properties lookup are provided by my Java Class, as you can see here (where i is a variable in a th:each loop):

th:text="#{${i.nameKey}}"
public String getNameKey() {
    // getKeyPrefix() generates a unique name from the class attributes
    return getKeyPrefix() + ".name";
}

This works fine.

Now I want to check if the value in the messages.properties file is null or empty for the given key:

th:if="${#messages.msg(i.nameKey) != null AND NOT #string.isEmpty(#messages.msg(i.nameKey))}"

But i can't pass the messages object into the isEmpty method. Any idea?

Thanks!


Solution

  • #messages.msg does not return null if the key is missing. From the docs:

    If a message is not found, a default message (like '??msgKey??') is returned.

    You should use #messages.msgOrNull instead. As for the second part of the question, there is no reason you can't combine #utility objects. That being said, it looks like you have a typo: the utility object #string does not exist, but #strings does.

    th:if="${#messages.msgOrNull(i.nameKey) != null AND NOT #strings.isEmpty(#messages.msgOrNull(i.nameKey))}"