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

</div>

Now when we run our application with -Dspring.profiles.active=production 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

</div>

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

some.string.property=String text
some.boolean.property=false
some.int.property=123456

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

<div>
    <p th:text="${@environment.getProperty('some.string.property')}"></p>
    <p th:text="${@environment.getProperty('some.boolean.property')}"></p>
    <p th:text="${@environment.getProperty('some.int.property')}"></p>
</div>

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

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 }}