Home Java Thymeleaf Tutorial:Chapter 5 Setting Attribute Values

Thymeleaf Tutorial:Chapter 5 Setting Attribute Values

by admin

Table of contents

5 Setting attribute values

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

5.1 Setting the value of any attribute

Let’s say our site publishes a newsletter and we want users to be able to subscribe to it, so we create a 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 with Thymeleaf, this template starts as a static prototype rather than a web application template. First, the actionattribute in our form is statically linked to the template file itself, so there’s no room for a useful URL rewrite. Second, the value attribute in the submit button allows you to display text in English, but we’d like it to be internationalized.
Then we use the attribute th:attr , capable of changing the value of the attributes of the tags in which it is set :

<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 pretty simple : th:attr takes an expression that executes and assigns the resulting value to the attribute. By creating appropriate controller and message files, the result of the file processing is :

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

In addition to the new attribute values, you can also see that the application context name was automatically added to the URL base in /gtvg/subscribe, as described in the previous chapter.
But what if we wanted to install more than one attribute at a time? XML rules don’t allow you to set an attribute twice in a tag, so th:attr will take a comma-separated list of assignments, such as :

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

Given the necessary message files, this will output :

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

5.2 Setting a value for certain attributes

By now you might think that something like :

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

is a pretty ugly piece of markup. Specifying a destination inside an attribute value can be very practical, but it’s not the most elegant way to create templates if you have to do it all the time.
Thymeleaf agrees with you, and that is why th:attr is unlikely to be used in templates. Usually you will use other attributes th:* whose job is to customize certain attributes of the tag (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}"/>

This looks so much better! Let’s try doing the same thing with the attribute action 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 exactly the same attributes :

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

There are quite a few such attributes, each targeting a specific HTML5 attribute:

th:abbr th:accept th:accept-charset
th:accesskey th:action th:align
th:alt th:archive th:audio
th:autocomplete th:axis th:background
th:bgcolor th:border th:cellpadding
th:cellspacing th:challenge th:charset
th:cite th:class th:classid
th:codebase th:codetype th:cols
th:colspan th:compact th:content
th:contenteditable th:contextmenu th:data
th:datetime th:dir th:draggable
th:dropzone th:enctype th:for
th:form th:formaction th:formenctype
th:formmethod th:formtarget th:fragment
th:frame th:frameborder th:headers
th:height th:high th:href
th:hreflang th:hspace th:http-equiv
th:icon th:id th:inline
th:keytype th:kind th:label
th:lang th:list th:longdesc
th:low th:manifest th:marginheight
th:marginwidth th:max th:maxlength
th:media th:method th:min
th:name th:onabort th:onafterprint
th:onbeforeprint th:onbeforeunload th:onblur
th:oncanplay th:oncanplaythrough th:onchange
th:onclick th:oncontextmenu th:ondblclick
th:ondrag th:unsupported th:ondragenter
th:ondragleave th:ondragover th:ondragstart
th:ondrop th:ondurationchange th:onemptied
th:onended th:onerror th:onfocus
th:onformchange th:onforminput th:onhashchange
th:oninput th:oninvalid th:onkeydown
th:onkeypress th:onkeyup th:onload
th:onloadeddata th:onloadedmetadata th:onloadstart
th:onmessage th:onmousedown th:onmousemove
th:onmouseout th:onmouseover th:onmouseup
th:onmousewheel th:onoffline th:ononline
th:onpause th:onplay th:onplaying
th:onpopstate th:onprogress th:onratechange
th:onreadystatechange th:onredo th:onreset
th:onresize th:onscroll th:onseeked
th:onseeking th:onselect th:onshow
th:onstalled th:onstorage th:onsubmit
th:onsuspend th:ontimeupdate th:onundo
th:onunload th:onvolumechange th:onwaiting
th:optimum th:pattern th:placeholder
th:poster th:preload th:radiogroup
th:rel th:rev th:rows
th:rowspan th:rules th:sandbox
th:scheme th:scope th:scrolling
th:size th:sizes th:span
th:spellcheck th:src th:srclang
th:standby th:start th:step
th:style th:summary th:tabindex
th:target th:title th:type
th:usemap th:value th:valuetype
th:vspace th:width th:wrap
th:xmlbase th:xmllang th:xmlspace

5.3 Setting multiple values at once

There are two rather special attributes called th:alt-title and th:lang-xmllang which can be used to specify two attributes 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}" />

to this :

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

5.4 Add pre- and -after

Thymeleaf also offers the attributes th:attrappend and th:attrprepend which add (suffix) or add (prefix) the result to existing attribute values.
For example, you might want to store the name of the CSS class to be added for one of your buttons in a context variable, since the specific CSS class to be used will depend on what the user has done before :

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

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

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

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

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

(Don’t worry about the meaning of th:each This is an iteration attribute, and we’ll talk about it later).

5.5 Boolean Attributes with Fixed Value

HTML has the concept of boolean attributes that are only activated if their value is "true". In XHTML, these attributes take only one value, which is.
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 that if its value is "true" the attribute will be set to its fixed value, and if it is "false" the attribute will not be set :

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

The following fixed-value logical attributes exist in Standard Dialect :

th:async th:autofocus th:autoplay
th:checked th:controls th:declare
th:default th:defer th:disabled
th:formnovalidate th:hidden th:ismap
th:loop th:multiple th:novalidate
th:nowrap th:open th:pubdate
th:readonly th:required th:reversed
th:scoped th:seamless th: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 no th:* a specific processor in Standard Dialect.
Something like this :

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

The result is :

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

5.7 Support for HTML5-friendly attributes and element names

You can also use a completely different syntax to apply processors to your templates in a more HTML5-friendly way.

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

Syntax data-{prefix}-{name} is the standard way to write custom attributes in HTML5, without requiring developers to use namespaced ones such as th:*. Thymeleaf makes this syntax automatically available for 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 element th:block (or th-block ), which will be explained in the next section.
Important : this syntax is an addition to namespaced th:*, it does not replace it. There is no intention to drop the namespaced syntax altogether in the future.

You may also like