Spring MVC part IV: ThymeLeaf advanced usage

This post follows on from the previous post on Thymeleaf integration with Spring MVC.

Today we’ll look at some advanced features of Thymeleaf

Please note that all the examples in this post can be found in a demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo

I Fragments inclusion

All the examples in this chapter can be found in the demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo, as example4.

A) General usage

A notheworthy templating engine has to provide a fragment system to avoid duplicating code. Fortunately Thymeleaf is shipped with a fragment inclusion system we’ll see shortly.

The main entry point for fragment inclusion is the th:include attribute. The syntax is: th:include=”fragment_file :: fragment_name|[DOM_selector].

The fragment_name or DOM_selector will be used to select the DOM object in the fragment_file file and inject it in the current document. The expression parsing and variable resolution will be performed after the fragment injection, not before. Please note that the DOM_selector needs to be put in square brackets. The DOM_selector uses a subset of XPath syntax, more details here.

Let’s define a template file common.html used as fragment container:

<html xmlns="http://www.w3.org/1999/xhtml"
<head id="headerFragment" th:fragment="headerFragment">
	<link rel="stylesheet" href="../assets/css/bootstrap.css" th:href="@{/assets/css/bootstrap.css}" />
	<link rel="stylesheet" href="../assets/css/thymeleaf-demo.css" th:href="@{/assets/css/thymeleaf-demo.css}" />
	<div class="container">

Please notice the usage of th:fragment to define the fragment_name.

Now let’s write an example4.html page to test it:

<head th:include="fragment/common :: headerFragment" />
<div class="container">
	<div class="hero-unit">
	    <h1>ThymeLeaf is awesome !</h1>
	    <p>This is a simple hero-unit layout to demonstrate the fragment inclusion system</p>
	    	<a class="btn btn-primary btn-large" href="http://www.thymeleaf.org" target="_blank">
	    	Learn more about ThymeLeaf ...

headerFragment indicates the fragment_name defined in the common.html file previously.

If we wish to use DOM_Selector instead of fragment_name, the example4.html page should be modified as follow:

<head th:include="fragment/common :: [//head]" />

In this case there is no need to define the fragment_name with th:fragment in the common.html file.

B) Fragment container

With the powerfull selection mechanism for fragment, we can define several fragments in a same container file and include them in any of our page.

Let’s define a footer fragment in common.html

<footer id="center-footer">
	<div id="footerText" class="span12" >Copyright 2012 <a href="https://doanduyhai.wordpress.com">doanduyhai</a> |
       	 	<a href="https://github.com/doanduyhai/ThymeLeafDemo">Fork ThymeLeaf Demo on Github</a> |
        	<a href="https://twitter.com/#!/doanduyhai">Follow @doanduyhai on Twitter</a>

And then include it in our example4.html page:

<div th:include="fragment/common :: [//footer[@id='center-footer']]"></div>

Please note the quite verbose DOM selector expression to select the footer element. A simpler expression like “[//footer]” would be sufficient but I let it as is for the tutorial purpose.

C) Static preview and fragment inclusion

There is one problem with our fragment inclusion, it does not work at all for static page preview.

Below is the static display of the previous example:


The rendering at runtime is:


The reason of this discrepancy is that in the static version the CSS styles are not available since there is no fragment inclusion.

To fix this, we simply add the stylesheet <rel> tags in the header of the static page. All this will be removed anyway at runtime by the fragment inclusion.

Edit: I’ve been informed by Daniel Fernández and Brian Keeter about Thymol,a javascript-base solution to perform fragment inclusion for static template preview. So there is no restriction anymore for static fragment inclusion.


II Thymeleaf and Spring EL (SpEL)

All the examples in this chapter can be found in the demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo, as example5.

When used in conjunction with Spring MVC, the default dialect used in the template files is Spring EL. It leverages Thymeleaf and offers a tremendous flexibility to manipulate data directly in the view.

A) Bean references & method invocation

Thymeleaf exposes a special object, beans, to let you access all Spring beans in the current application context.

Let’s define a dateFormatter bean as follow:

<bean id="dateFormatter" class="doan.thymeleaf.demo.util.DateFormatter"/>

The source code of the bean is quite straightforward:

public class DateFormatter
	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public String getCurrentDate()
		return new DateTime(new Date()).toString(DATE_FORMAT);

This bean defines a public getCurrentDate() method we’ll use in our page.

<span th:text="${'Current date is : '+beans.dateFormatter.getCurrentDate()}">Current date is : 2012-04-14 17:30:00</span>

To access our bean named “dateFormatter“, we have to use the helper object “beans” provided by Thymeleaf. Under the hood beans is simply a Map which contains all references to the beans registered in the Spring context. There is really no magic here.

B) Static fields & methods

Spring EL provides the T( ) operator to access a class level(static) field or method.

<span th:text="${'The application name is : '+T(doan.thymeleaf.demo.util.Constants).APPLICATION_NAME}">The application name is : Test</span>

This can be usefull to access some constants defined in the classpath without having to add the constant in the Model map.

C) Projection & selection on collection

Projection and selection are vocabulary from the relational world (SQL). Selection corresponds to row filtering (with WHERE clause) and projection corresponds to column restriction (the SELECT clause).

When applied to a collection of elements in Java:

  • selection means filtering each element of the collection using its properties. The result of such an operation is a subset of the initial collection, only matching elements are retained


  • projection means filtering the property of each element in the collection. The result of a projection operation is a a new collection, with the same number of elements than the original one, but containing only the filtered property of the elements, not the whole element object itself

The syntax of the selection operator is : collection.?[property == value]
The syntax of the projection operator is : collection.![property]

Of course, for selection we can combine several conditions with logical operators (and, or, not) to filter on different properties. Similarly, with the projection, it is possible to fetch several properties by concatenating them.

An example is better than words, let’s see those in action:

<tr th:each="artist,rowStat : ${listArtits.?[alive == true]}">
	<td class="center middle" th:text="${rowStat.count}">1</td>
	<td class="center middle" th:text="${artist.name}">Michael Jackson</td>
	<td class="center middle" th:text="${artist.discography}">Got to Be There, Ben, Music &amp; Me, Forever Michael...</td>
	<td class="center middle" th:text="${artist.bio}">Michael Joseph Jackson (August 29, 1958 - June 25, 2009) was an American recording artist, entertainer, and businessman...</td>

Above we only select alive artists.

If we want to display only the firstname and lastname of the artist, we can “project” on both properties:

<tr th:each="artist,rowStat : ${listArtits.![firstname+' '+lastname]}">
	<td class="center middle" th:text="${rowStat.count}">1</td>
	<td class="center middle" th:text="${artist}">Michael Jackson</td>

Of course it is possible to combine selection and projection:

<tr th:each="artist,rowStat : ${listArtits.?[alive == true].![firstname+' '+lastname]}">
	<td class="center middle" th:text="${rowStat.count}">1</td>
	<td class="center middle" th:text="${artist}">Michael Jackson</td>

Please note that the order between projection and selection is important. If you “project” on a property before doing selection, the latter can only filter on this same property.


III Inlining & Javascript tricks

All the examples in this chapter can be found in the demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo, as example6.

A) Text inlining

Text inlining means that instead of being evaluated in the th:text attribute, the tag body is parsed by the engine and evaluated.

To do text inlining, we use the th:inline attribute with th:inline=”text”. The expression to be evaluated should be enclosed in double square brackets [[ ]]

<span th:inline="text">[[${'Current date is : '+beans.dateFormatter.getCurrentDate()}]]</span>

The drawback of text inlining is the static page preview. What is displayed is the inlined expression itself:


B) Script inlining and variables propagation

With Thymeleaf it is also possible to evaluate SpEL expression inside a script tag. For the moment only Javascript and Google Dart are supported as script languages. To inline script, the value of th:inline should be set to “script”. The script code should also be enclosed between /*<![CDATA[*/ and /*]]>*/. Each SpEL expression inside the script body should be enclosed in /*[[ ]]*/

	<button id="actionButton" type="button" onclick="displayApplicationName();">Get Application name</button>
	<span id="displaySpan">Application name : </span>
<script th:inline="javascript">

	var applicationName = /*[[${T(doan.thymeleaf.demo.util.Constants).APPLICATION_NAME}]]*/ "Test";

	function displayApplicationName()
		document.getElementById('displaySpan').innerHTML='Application name : '+applicationName;

One important thing to notice with script inlining is that it still works for static preview. Indeed the Javascript variable applicationName is declared with an inline expression followed by a default value: “Test“.

When displayed in a browser, the inlined expression between /*[[ ]]*/ will be ignored (considered as a comment) so the default value applies. A browser will see the variable declaration as:

var applicationName = “Test”;

At runtime, Thymeleaf will evaluate the inlined expression and everything that follows this expression will be stripped out. Thymeleaf will see the variable declaration as:

var applicationName = ${T(doan.thymeleaf.demo.util.Constants).APPLICATION_NAME}

Thus script inlining offers us a way to propagate variables defined in the server up to the Javascript layer. But what is it for ?

The idea behind the variables propagation is to define a variable value at only one place, on the server side. If they are defined at many places, changing them required code modification everywhere, with the risk of code discrepancy.

IV Helper objects awesomeness

All the examples in this chapter can be found in the demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo, as example2.

Thymeleaf was designed with productivity in mind. It comes with numerous helper objects to simplify developers’ life. Below is the complete list of available helper objects and their function:

  • dates : utility methods for java.util.Date objects: formatting, component extraction, etc.
  • calendars : analogous to #dates, but for java.util.Calendar objects.
  • numbers : utility methods for formatting numeric objects.
  • strings : utility methods for String objects: contains, startsWith, prepending/appending, etc.
  • objects : utility methods for objects in general.
  • bools : utility methods for boolean evaluation.
  • arrays : utility methods for arrays.
  • lists : utility methods for lists.
  • sets : utility methods for sets.
  • maps : utility methods for maps.
  • aggregates : utility methods for creating aggregates on arrays or collections.
  • messages : utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.

It will take hours to go through all of them so we’ll only focus on the most usefull utility functions.

  • date formatting: ${#dates.format(date, ‘dd/MMM/yyyy HH:mm’)}
  • current time: ${#dates.createNow()}
  • empty or null string check: ${#strings.isEmpty(name)}
  • string operations: #strings.indexOf, #strings.substring, #strings.replace, #strings.prepend, #strings.append, #strings.toUpperCase, #strings.toLowerCase, #strings.trim, #strings.length, #strings.abbreviate
  • string collection manipulation: #strings.listJoin, #strings.arrayJoin, #strings.setJoin, strings.listSplit, strings.arraySplit, strings.setSplit
  • object null safe: ${#objects.nullSafe(obj,default)}
  • list manipulation: ${#lists.size(list)}, ${#lists.isEmpty(list)}, ${#lists.contains(list, element)}
  • message retrieval: ${#messages.msg(‘msgKey’)}, ${#messages.msg(‘msgKey’, param1, param2)}

Let’s put them in action in an example:

<div class="alert"
	th:if="${results != null and #lists.isEmpty(results) and searchAction != null}">
    	<strong>No result found!</strong> Please retry with different search filter(s).
<section id="searchResult">
	<table id="resultTable"
		class="table table-bordered"
		th:if="${results != null and not #lists.isEmpty(results)}">
			<tr class="center middle">
			<tr th:each="artist,rowStat : ${results}">
				<td class="center middle" th:text="${rowStat.count}">1</td>
				<td th:text="${artist.name}">Mariah Carey</td>
				<td th:text="${#strings.abbreviate(#strings.listJoin(artist.discography,', '),30)}">Mariah Carey, Emotions, Music Box, Merry Christmas, DayDream, Butter...</td>
				<td th:text="${#strings.abbreviate(artist.bio,100)}">Mariah Carey (born March 27, 1970) is an American singer...</td>

At lines 2 & 8 we use #lists.isEmpty() to check for result emptiness. Unfortunately this method is not null safe so a prior null check is required.

Edit: from ThymeLeaf version 2.0.7, null check is no longer required because isEmpty() methods in #arrays, #lists, #maps and #sets are null-safe.

At line 21 we use #strings.listJoin() to concatenate all the discography into a string and then apply #strings.abbreviate() to shorten it.

Below is the render at runtime:

V Spring Security integration

All the examples in this chapter can be found in the demo application on GitHub https://github.com/doanduyhai/ThymeLeafDemo, as example7.

Last but not least, we’ll see how Thymeleaf can be integrated with Spring Security. If you are an attentive reader if this blog, maybe you already read the post on Spring Security taglibs for JSP. If not I urge you to do so.

The problem is that this very convenient tag lib is only available for JSP, not for Thymeleaf. However with the flexibility of Spring MVC, it is possible to inject a security object in the Model map so it becomes available for the template engine at runtime.

The original solution was found by Zemi on the Thymeleaf forum, so the credits go to him. I only briefly expose the solution here.

First we need to create a custom interceptor for Spring MVC. This interceptor’ job is to inject the security object and make it available to the template engine:

public class SecurityInterceptor extends HandlerInterceptorAdapter
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
		if (modelAndView != null)
			ServletRequest req = (ServletRequest) request;
			ServletResponse resp = (ServletResponse) response;
			FilterInvocation filterInvocation = new FilterInvocation(req, resp, new FilterChain()
				public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException
					throw new UnsupportedOperationException();

			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			if (authentication != null)
				WebSecurityExpressionRoot sec = new WebSecurityExpressionRoot(authentication, filterInvocation);
				sec.setTrustResolver(new AuthenticationTrustResolverImpl());
				modelAndView.getModel().put("sec", sec);

Basically we just inject into the Model map a WebSecurityExpressionRoot variable called “sec“.

Interceptor configuration for Spring MVC:

<bean id="securityInterceptor" class="doan.thymeleaf.demo.security.SecurityInterceptor"/>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
	<property name="interceptors">
			<ref bean="securityInterceptor" />

Now in the template file we can access the “sec” variable:

<div class="span10 offset1">
	<span class="alert alert-success" th:text="${'User login : '+sec.principal.username}">User login : foo bar</span>
	<span class="alert alert-success" th:text="${'User authorities : '+ #strings.listJoin(sec.principal.authorities,',')}">User authorities : simple user</span>

That’s it folks!

About DuyHai DOAN
Cassandra Technical Evangelist. LinkedIn profile : http://fr.linkedin.com/pub/duyhai-doan/2/224/848. Follow me on Twitter: @doanduyhai for latest updates on Cassandra

10 Responses to Spring MVC part IV: ThymeLeaf advanced usage

  1. Daniel Fernández says:

    That “#lists.isEmpty” not being null-safe should be changed, it is not intuitive. I will modify it for next versions of Thymeleaf. Thanks for your very nice articles! :-)

  2. thymeleafer says:

    thank you sooooo much !!!

  3. Fran Serrano says:

    Thanks for this very nice article for people that is already playing seriously with Thymeleaf. Promising future for this framework thanks to Daniel Fernández, the Thymeleaf team and bloggers like you ;O)

  4. xtra size says:

    Appreciation to my father who told me on the topic of this weblog, this webpage
    is actually awesome.

  5. Agnes says:

    For hottest news you have to pay a visit world wide web
    and on world-wide-web I found this web page as a best web page for newest updates.

  6. peter says:

    thank you!
    chapter iii.B “enclose script” solved my problem where a style attribute inside a div tag inside a literal inside javascript code inside thymeleaf template broke either thymeleaf parsing at ‘ or the browser “SyntaxError: missing ; before statement”.

    original line was from a jqwidgets example on computed cell values:

    return “” + dataAdapter.formatNumber(total, “c2”) + “”;


  7. What’s up to every one, the contents present at this site are truly
    awesome for people experience, well, keep up the good work fellows.

  8. Alexander says:

    I has googled you post then looking for information about usage of static functions inside Thymeleaf.
    Thank you! Nice series about Thymeleaf!

  9. Pingback: YinOva Center

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 54 other followers

%d bloggers like this: