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=”http://www.thymeleaf.org”>

 

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.

  @Controller
  public class HomeController {

     @GetMapping(“/”)
     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;

  @Controller
   public class HomeController {
       
@GetMapping("/")
      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="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Thymeleaf Demo</title>
</head>

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

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

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

</body>
</html>


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.

References

Thymeleaf website

Spring Tool Suite

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

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


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


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


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

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


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More


How to contribute to open source

  • opensource contribute participate foss

I could see many many students posting this question in many forums, I want to contribute to open source but How to contribute? There are many ways to do that. I have listed a few and I hope it might be useful.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More