Thymeleaf utility methods for messages

August 04, 2019 No comments Thymeleaf Utility Messages

1. Introduction

Thymeleaf is a template engine for Java applications that comes with many utility methods which allows developers to use complex logic inside variables expressions. In this article, we will present #messages utility that provide methods for obtaining externalized messages. The implementation of those utility functions can be found in official Thymeleaf GitHub Repository.

2. Available utility methods for messages

Method Purpose Description
${#messages.msg('msgKey')}
${#messages.msg('msgKey', param1)}
${#messages.msg('msgKey', param1, param2)}
${#messages.msg('msgKey', param1, param2, param3)}
${#messages.msgWithParams('msgKey', new Object[] {param1, param2})}
Obtain externalized message for one key Method can receive a single key or a key plus arguments. If a message is not found, a default message (like '??msgKey??') is returned.
${#messages.arrayMsg(messageKeyArray)}
${#messages.listMsg(messageKeyList)}
${#messages.setMsg(messageKeySet)}
Retrieve externalized messages for key list These methods received array/list/set of keys and it will return an array/list/set of externalized messages
${#messages.msgOrNull('msgKey')}
${#messages.msgOrNull('msgKey', param1)}
${#messages.msgOrNull('msgKey', param1, param2)}
${#messages.msgOrNull('msgKey', param1, param2, param3)}
${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2})}
${#messages.arrayMsgOrNull(messageKeyArray)}
${#messages.listMsgOrNull(messageKeyList)}
${#messages.setMsgOrNull(messageKeySet)}
Obtain externalized messages or null In this case if message for specified key is not found we will get Null instead of default message.

3. Conclusion

In this article, we presented messages utility available for Thymeleaf templates. This utility is an alternative of using #{...} syntax for th:text attributes. In non-standard situations, direct methods for obtaining externalized messages will be helpful.

{{ message }}

{{ 'Comments are closed.' | trans }}