How to get environment in Thymeleaf

January 04, 2020 No comments Thymeleaf Environment Parameters

1. Introduction

Sometimes there is a need to include a specific piece of code on the website only on the production environment (for example Google Analitycs code).Thymeleaf allows us to create conditional statements using selected profile on Spring application server, so we can hide/show elements depending on runtime configuration.

2. Access Environment bean

In Thymeleaf we can access all available Spring beans using @ symbol. Environment object that represents the environment in which the current application is running, is also available. We can use it to check currently selected profile and control the visibility of the elements accordingly.

Environment object has implemented a method getActiveProfiles() which returns an array of Strings (active profiles). If we use only one profile at a time the code that checks if it is a production profile will look like the following:

<div th:if="${!#arrays.isEmpty(@environment.getActiveProfiles()) && @environment.getActiveProfiles()[0] == 'production'}">

    This is the production profile


Now when we run our application with parameter the text This is the production profile will be displayed in the DIV element.

If more than one profile is active at a time, we will have to use contains method from the #arrays utility class.

<div th:if="${!#arrays.isEmpty(@environment.getActiveProfiles()) && #arrays.contains(@environment.getActiveProfiles(), 'production')}">

    This is the production profile


Environment bean is also helpful to access any other application property from file. text

To get application properties value we should call environment.getProperty() method:

    <p th:text="${@environment.getProperty('')}"></p>
    <p th:text="${@environment.getProperty('')}"></p>
    <p th:text="${@environment.getProperty('')}"></p>

<section th:if="${@environment.getProperty('')}">
    Section visible

3. Conclusion

In this short article, we discussed how to get the selected environment in Thymeleaf templates. We presented the Environment bean that can be used to access the active profile.

The full code that was used in this article can be found in our GitHub repository.

{{ message }}

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