Thymeleaf - Text display, Iteration and Conditionals

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.


First, to use Thymeleaf, we need to declare its XML namespace in the html tag, as follows:

<html xmlns:th=””>


1. Text display

When using Thymeleaf, we can display text in many ways. We will discuss all possible cases. To display text, we need to use th:text attribute.


Displaying static text

A text literal can be accessed by using ‘<string>’ as value of th:text attribute, where <string> indicates the text we want to display. Note: Text literal should be enclosed between single quotes. This, in turn, is placed between double quotes to form the value of th:text attribute.

<li th:text=”’Static Text’”></li>


During run-time, this will be interpreted as:

<li>Static Text</li>


Display text or content from a model / controller

If we want to display dynamic content then the content can be passed as model attribute.

  public class HomeController {

     public String home(Model model) {
           model.addAttribute(“description”, “Dynamic Text From Controller”);
           return “home”;

A model attribute can be accessed by using ${<model-name>} as value of th:text attribute, where <model-name> indicates the name of the model attribute.

<li th:text=”${description}”></li>


During run-time, this will be interpreted as:

<li> Dynamic Text From Controller </li>


Displaying text from message properties file

Another scenario is to access text from message resource. Few content which require localization will be put in message resources so that localized strings can be easily displayed. Consider we have following content in the message resource file:

menu-id-about-us=About Us
menu-id-contact-us=Contact Us

A message can be accessed by using #{<message-id>} as value of th:text attribute, where <message-id> indicates the key.

<li th:text=”#{menu-id-contact-us}”></li>


During run-time, this will be interpreted as:

<li> Contact Us</li>


2. Iteration

To iterate over a list, we can use th:each, as shown below. Let’s say we have a list called suits (card game). If we want to render a list-item for each element of suits, then th:each will iterate and render the content.

<li th:text=”${suit}” th:each=”suit: ${suits}”></li>


Here, th:each causes suit variable to have current element value for each iteration, and th:text causes that value to be displayed as list element text.

  • Diamond
  • Club
  • Heart
  • Spade

3. Conditionals

We can make a html tag to conditionally render by using th:if attribute, as shown below:

<p th:text="'2 is greater than 1'" th:if="2 > 1"></p>

This Thymeleaf snippet causes rendering of Text “2 is greater than 1” if the condition in value of th:if is true (which is yes in this case). The text will not be rendered if the condition is false.

Integrate Thymeleaf with Spring

Install Spring Tool Suite

Download Spring Tool Suite and expand the zip file in desired location.

Create the project

  1. Open Spring Tool Suite (i.e., SpringToolSuite4.exe under installed location)
  2. From menu, File > New > Spring Starter Project
  3. In New Spring Starter Project wizard:
    1. In Name field, provide a name. (e.g., TextDemo)
    2. Provide values for Group and Artifact (e.g., org.example for Group, text-demo for Artifact)
    3. Provide value for Package field, (e.g., example.text_demo)
    4. Click Next
  4. In resulting ‘New Spring Starter Project Dependencies’ page:
    1. In Available: field, type Thymeleaf
    2. The list below that will now show Thymeleaf as an entry. Select the checkbox for that entry
    Click Finish. Thymeleaf-based web application project will be created

Create a Controller

  1. In Package Explorer view, expand the tree to select package example.text_demo under src/main/java folder.
  2. Right-click the package. In the resulting pop-up menu, select New > Class.
  3. In the resulting ‘New Java Class’ wizard:
    1. Provide value for Name field (e.g., HomeController).
    2. Click Finish. Class HomeController will be created and opened in editor.
  4. Replace the contents of the file with the following code
  package com.example.text_demo;

  import org.springframework.stereotype.Controller;
  import org.springframework.ui.Model;
  import org.springframework.web.bind.annotation.GetMapping;

   public class HomeController {
      public String home(Model model) {
         model.addAttribute(“description”, “Dynamic Text From Controller”);
         List<String> suits = new ArrayList<String>(Arrays.asList("Diamond", "Club", "Heart", "Spade"));
         model.addAttribute("suits", suits);
        return "home";

Create a Thymeleaf template

  1. In Package Explorer view, expand the tree to select folder templates under src/main/resources
  2. Right-click on templates. In the pop-up menu, select New > File.
  3. In resulting New File wizard:
    1. Provide value for File name: field (e.g., html).
    2. Click Finish. File html opens in editor.
  4. Replace the contents of html with the following:
 <!DOCTYPE html>
<html xmlns:th="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Thymeleaf Demo</title>

<li>Default Text</li>
<li th:text="'Static Text'"></li>
<li th:text="${description}"></li>
<li th:text="#{menu-id-contact-us}"></li>

<li th:text="${suit}" th:each="suit: ${suits}"></li>

<p th:text="'2 is greater than 1'" th:if="2 > 1"></p>


Run the application

  1. From Menu, select File > Save All.
  2. In Package Explorer view, right click on project node (e.g., TextDemo).
  3. In resulting pop-up menu, select Run As > Spring Boot App.
  4. Console view shows logs and will state that Tomcat started on port 8080.
  5. Now open a web browser and navigate to http://localhost:8080.


Thymeleaf website

Spring Tool Suite



We publish blog post about open source products. If you are interested in sharing knowledge about open source products, please visit write for us

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More

PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More

New Open Source Web Browser Engine from Google and Mozilla

  • browser browser-engine

Web Browser engine used to render the page from HTML, CSS and Javascript. The browsers are one of the most important tool to view the web and it is must have software in Desktop and Mobile. These new browsers will take advantage of tomorrow’s faster, multi-core, heterogeneous computing desktop and mobile architectures.

Read More

Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More

LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More

Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More

Free Open Source Code Search Engines

  • code-search code-search-engine search-engine

There are couple of sites which indexes the open source code and provides support to search code. Recently Google announced that they removed code search support from Google code. This article provides pointer for code search engine sites.

Read More

Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More

Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More

8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More

An introduction to LucidWorks Enterprise Search

  • lucene solr search engine enterprise

Lucidworks Enterprise search solution is built on top of Apache Solr. It scales seamlessly w/sub-second response times under extreme query loads for multi-billion document collections. It has user friendly UI, which does all the job of configuration and search.

Read More

Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More

Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More

An introduction to web cache proxy server - nuster

  • web-cache proxy-server load-balancer

Nuster is a simple yet powerful web caching proxy server based on HAProxy. It is 100% compatible with HAProxy, and takes full advantage of the ACL functionality of HAProxy to provide fine-grained caching policy based on the content of request, response or server status. This article gives an overview of nuster - web cache proxy server, its installation and few examples of how to use it.

Read More

Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More

Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More

8 Best Open Source Searchengines built on top of Lucene

  • lucene solr searchengine elasticsearch

Lucene is most powerful and widely used Search engine. Here is the list of 7 search engines which is built on top of Lucene. You could imagine how powerful they are.

Read More

AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart php

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More

Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.