Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic th:attr definition for multiple attributes in one html element with thymeleaf

Tags:

thymeleaf

I am trying to generalize form fields for a form. I want to have different parsley.js validation requirements. There are 2 non-standard attributes that I want to dynamically append to the input field: required and data-parsley-range. An example of a simple html without thymeleaf would be:

<input type=text required data-parsley-range=[1,100] />

I've tried the following with thymeleaf:

<input class="form-control" fieldType="text" th:attr="required=${field.isRequired ? 'required' : null}" 
th:attr="data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}"/>

But I've got an error that th:attr is defined multiple times.

So my question is: How can I define multiple attributes with help of th:attr in a single html element?

My additional question is: How can I conditionally place the attributes? For example I don't want to write required='required' at all if I can avoid it, same applies to the range.

like image 366
Joe Essey Avatar asked Aug 05 '15 19:08

Joe Essey


1 Answers

The straight solution is to use a comma , to separate multiple attributes.

<input th:attr="required=${field.isRequired ? 'required' : null}, data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}" />

Alternatively, if you want to keep attributes separately for better reading purposes, you can use th:attrappend:

<input th:attr="required=${field.isRequired ? 'required' : null}" 
th:attrappend="data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}" />
like image 106
nmy Avatar answered Nov 16 '22 22:11

nmy