Thymeleaf Conditions, Comma Control and Glyphicons as List Styles

I don’t like long Post Titles otherwise the full title of this post would be Conditional Content Display, Comma Management and using Bootstrap Glyphicons as List Styles with Thymeleaf, Spring and CSS. That would more accurately describe the topics we’ll cover in this post, or in list form:

  1. How Spring Model functions simplify Thymeleaf conditional statements like IF and SWITCH
  2. How to easily separate a Spring Model Content List display with commas
  3. How to use Bootstrap Glyphicons as HTML List Icons

Here’s a look at the updated Product Display page of NixMash Spring and available online here.

Thymeleaf IF and SWITCH with Spring

We’re going to see how Spring Model functions simplify Thymeleaf Conditional Statements like IF and SWITCH. Here is an IF statement on our HTML page. The key to simplicity is the first line, th:if=”{product.hasFeatures()}”.

We can keep our HTML clean with a simple function added to our Spring Model.

public boolean hasFeatures() {
return (this.features != null);
}

We use the same principle for a Thymeleaf SWITCH statement, adding a hasCategories() function to our Product Model. It looks much like our hasFeatures() function so we won’t repeat ourselves. As a sidebar, the example below is a good example of using default Thymeleaf {true} and {false} conditions. If categories exist we display them as a comma-delimited list (more on those commas in a second), and if no categories, a Spring Resource Message.

Comma Control

Here is a simple way to manage the display of commas in a Spring Data List so that there is no comma after the last item. I hope you’re not disappointed with the solution, because it’s not sexy at all. Three letters: CSS.

First, the Thymeleaf iteration of categories shown above is th:each=”category : ${product.categories}” where we repeat an HREF link to a Product Categories page. The CSS:

ul.catlist { list-style: none; margin: 0; padding: 0; }
ul.catlist li { display: inline; }
ul.catlist li a:after { content: ","; }
ul.catlist li:last-child a:after { content: ""; }

Why make these things hard?

Using a Bootstrap Gyphicon for HTML List Icons

Look at these cool Bootstrap Gyphicons as List Style for our Product Features. Little red hearts!

If you don’t like hearts, there are plenty of other Gyphicon options shown here. Simply grab the CSS Rule content from the link and you’re good to go.

ul.featurelist {
	list-style: none;
	margin: 0;
	padding-left: 1em;
	padding-top: 0.1em;
	padding: .1em 0 .5em 1em;
} 

ul.featurelist li:before {
	content: "\e005";
	font-family: 'Glyphicons Halflings';
	font-size: 9px;
	float: left;
	margin-top: 7px;
	margin-left: -18px;
	color: #dd4814;
}

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.