We face a common scenario to display a control active or disabled on UI depending on model (Spring MVC) attributes. There are few examples to perform this in ThymeLeaf .
After some googling and going through ThymeLeaf documentation we found two different ways to perform this.
Make two HTML controls
The code snippet below displays HTML for two drop downs both having same id. I have removed some attributes for ease. The th:if condition allows only one to render at a given time. This if condition checks for model attribute actionType.
In case of Edit as actionType the rendered drop down is disabled with its current selection set in jQuery (Not displayed in snippet). The controls are bound to modelObjectList, a custom attribute in model object passed by Spring MVC. th:each loops through the collection and options are created with value and text (displayed as Code – description) and id.
Make use of ThymeLeaf tag with single HTML representation
The second and preferred way is to set th:disabled on drop down control. The value of disabled is set through model attribute isEnabled. You can set this model attribute on controller and you will be good to go for active or disabled drop downs.
For HTML input controls the same can be achieved by setting ThymeLeaf th:readonly attribute. An example of same is given below. isReadOnly is a custom attribute that you can add to Model in Controller. The control will render accordingly.