📜 ⬆️ ⬇️

Thymeleaf Tutorial: Chapter 5 Setting Attribute Values

Table of contents

5 Setting Attribute Values


In this chapter, we will explain how we can set (or change) attribute values ​​in markup.

5.1 Setting the value of any attribute


Let's say our site publishes a newsletter, and we want users to subscribe to it, so we create the template /WEB-INF/templates/subscribe.html with the form:

<form action="subscribe.html"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" /> </fieldset> </form> 

As in the case of Thymeleaf, this template begins, rather, as a static prototype, than a template for a web application. First, the action attribute in our form is statically linked to the template file itself, so there is no place for a useful URL rewriting. Secondly, the value attribute in the submit button allows you to display text in English, but we would like it to be internationalized.
')
Then use the th: attr attribute, which can change the value of the attributes of the tags in which it is installed:

 <form action="subscribe.html" th:attr="action=@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form> 

The concept is quite simple: th: attr accepts an expression that executes and assigns the resulting value to an attribute. Having created the corresponding controller and message files, the result of the file processing will be:

 <form action="/gtvg/subscribe"> <fieldset> <input type="text" name="email" /> <input type="submit" value="¡Suscríbe!"/> </fieldset> </form> 

In addition to new attribute values, you can also see that the application context name was automatically added to the URL database in / gtvg / subscribe, as described in the previous chapter.

But what if we wanted to set more than one attribute at a time? The XML rules do not allow you to set the attribute twice in the tag, so th: attr will take a list of assignments separated by commas, for example:

 <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /> 

Given the required message files, this will output:

 <img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" /> 

5.2 Setting Values ​​for Certain Attributes


By now, you might think that something like:

 <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> 

... a pretty ugly piece of markup. Specifying the destination within an attribute value can be very practical, but it’s not the most elegant way to create templates if you have to do this all the time.

Thymeleaf agrees with you, which is why th: attr is hardly used in templates. Typically, you will use other th: * attributes, the task of which is to configure certain attributes of the tag (and not just any attribute, such as th: attr).

For example, to set the value attribute, use the value th: value :

 <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/> 

It looks much better! Let's try to do the same with the action attribute in the form tag:

 <form action="subscribe.html" th:action="@{/subscribe}"> 

And do you remember these th: href that we put in our home.html before? These are the exact same attributes:

 <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li> 

There are quite a few such attributes, each of which is aimed at a specific HTML5 attribute:
th:abbrth:acceptth:accept-charset
th:accesskeyth:actionth:align
th:altth:archiveth:audio
th:autocompleteth:axisth:background
th:bgcolorth:borderth:cellpadding
th:cellspacingth:challengeth:charset
th:citeth:classth:classid
th:codebaseth:codetypeth:cols
th:colspanth:compactth:content
th:contenteditableth:contextmenuth:data
th:datetimeth:dirth:draggable
th:dropzoneth:enctypeth:for
th:formth:formactionth:formenctype
th:formmethodth:formtargetth:fragment
th:frameth:frameborderth:headers
th:heightth:highth:href
th:hreflangth:hspaceth:http-equiv
th:iconth:idth:inline
th:keytypeth:kindth:label
th:langth:listth:longdesc
th:lowth:manifestth:marginheight
th:marginwidthth:maxth:maxlength
th:mediath:methodth:min
th:nameth:onabortth:onafterprint
th:onbeforeprintth:onbeforeunloadth:onblur
th:oncanplayth:oncanplaythroughth:onchange
th:onclickth:oncontextmenuth:ondblclick
th:ondragth:ondragendth:ondragenter
th:ondragleaveth:ondragoverth:ondragstart
th:ondropth:ondurationchangeth:onemptied
th:onendedth:onerrorth:onfocus
th:onformchangeth:onforminputth:onhashchange
th:oninputth:oninvalidth:onkeydown
th:onkeypressth:onkeyupth:onload
th:onloadeddatath:onloadedmetadatath:onloadstart
th:onmessageth:onmousedownth:onmousemove
th:onmouseoutth:onmouseoverth:onmouseup
th:onmousewheelth:onofflineth:ononline
th:onpauseth:onplayth:onplaying
th:onpopstateth:onprogressth:onratechange
th:onreadystatechangeth:onredoth:onreset
th:onresizeth:onscrollth:onseeked
th:onseekingth:onselectth:onshow
th:onstalledth:onstorageth:onsubmit
th:onsuspendth:ontimeupdateth:onundo
th:onunloadth:onvolumechangeth:onwaiting
th:optimumth:patternth:placeholder
th:posterth:preloadth:radiogroup
th:relth:revth:rows
th:rowspanth:rulesth:sandbox
th:schemeth:scopeth:scrolling
th:sizeth:sizesth:span
th:spellcheckth:srcth:srclang
th:standbyth:startth:step
th:styleth:summaryth:tabindex
th:targetth:titleth:type
th:usemapth:valueth:valuetype
th:vspaceth:widthth:wrap
th:xmlbaseth:xmllangth:xmlspace

5.3 Setting multiple values ​​at once


There are two fairly special attributes called th: alt-title and th: lang-xmllang , which can be used to set two attributes at the same time at the same time. In particular:

th: alt-title will be set to alt and title .
th: lang-xmllang will install lang and xml: lang

For our GTVG homepage, this will allow us to replace this:

 <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /> 

... or this, which is equivalent to:

 <img src="../../images/gtvglogo.png" th:src="@{/images/gtvglogo.png}" th:title="#{logo}" th:alt="#{logo}" /> 

… on this:

 <img src="../../images/gtvglogo.png" th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /> 

5.4 Add before and after


Thymeleaf also offers th: attrappend and th: attrprepend attributes , which add (suffix) or add (prefix) the result to existing attribute values.

For example, you might want to save the name of the added CSS class for one of your buttons in a context variable, since the specific CSS class that will be used will depend on what the user did before:

 <input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" /> 

If you process this template with the variable cssStyle set to "warning", you will get:

 <input type="button" value="Do it!" class="btn warning" /> 

Standard Dialect also has two special add attributes: the th: classappend and th: styleappend attributes , which are used to add a CSS class or style fragment to an element without overwriting the existing ones:

 <tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'"> 

(Don't worry about the value of th: each . This is an iteration attribute, and we'll talk about that later.)

5.5 Boolean attributes with a fixed value


HTML has the concept of logical attributes that are activated only if their value is "true." In XHTML, these attributes take on only one value, which they are.

For example, check:

 <input type="checkbox" name="option2" checked /> <!-- HTML --> <input type="checkbox" name="option1" checked="checked" /> <!-- XHTML --> 


Standard Dialect includes attributes that allow you to set these attributes by condition, so if its value is “true”, the attribute will be set to its fixed value, and if it is equal to “false”, the attribute will not be set:

 <input type="checkbox" name="active" th:checked="${user.active}" /> 

Standard Dialect has the following logical attributes with a fixed value:
th:asyncth:autofocusth:autoplay
th:checkedth:controlsth:declare
th:defaultth:deferth:disabled
th:formnovalidateth:hiddenth:ismap
th:loopth:multipleth:novalidate
th:nowrapth:openth:pubdate
th:readonlyth:requiredth:reversed
th:scopedth:seamlessth:selected

5.6 Setting the value of any attribute (default attribute processor)


Thymeleaf offers a default attribute processor that allows us to set the value of any attribute, even if it doesn’t specify th: * specific processor in Standard Dialect.

Something like that:

 <span th:whatever="${user.name}">...</span> 

The result will be:

 <span whatever="John Apricot">...</span> 

5.7 Support for HTML5 Friendly Attributes and Element Names


You can also use a completely different syntax for applying processors to your templates in a more convenient way for HTML5.

 <table> <tr data-th-each="user : ${users}"> <td data-th-text="${user.login}">...</td> <td data-th-text="${user.name}">...</td> </tr> </table> 

The syntax data- {prefix} - {name} is the standard way to write custom attributes in HTML5, without requiring developers to use namespaced, such as th: *. Thymeleaf makes this syntax automatically available to all your dialects (not just Standard).

There is also a syntax for specifying custom tags: {prefix} - {name} , which follows the W3C Custom Elements specification (part of the larger W3C Web Components specification). This can be used, for example, for the th: block (or th-block ) element, which will be explained in the next section.

Important : This syntax is an addition to the namespaced th: *, it does not replace it. There is no intention at all to abandon the namespaced syntax in the future.

Source: https://habr.com/ru/post/351030/


All Articles