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:
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.
Environment
bean is also helpful to access any other application property from application.properties
file.
To get application properties value we should call environment.getProperty()
method:
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}