Conditional CSS Value Assignment with Thymeleaf

We had an interesting CSS issue come up today which, unlike 99% of CSS, qualifies as blog-worthy. [Elaine? Seinfeld?…]

We’re adding sidebar links to NixMash Spring Posts which appear only for logged-in users. The first is the user’s Liked Posts.

Here’s what the sidebar menu looks like to a user who is not logged-in. There’s no “Your Liked Posts” sidebar menu.

The Problem

The problem is that the sidebar elements are affixed and stop at a certain height from the top of the page. (See this NixMash post for details.) If you do much CSS then you know what’s coming: the affixed TagCloud area overlaps the sidebar menu when there are additional user menu items. I won’t show you a screenshot of that because it isn’t pretty.

The Fix

This is very cool stuff coming: Thymeleaf CSS Inlining with Conditional Variable Assignment! The code shown below is sitting in a Thymeleaf fragment called “sidebar” which is cool enough, I guess, but check out the th:with assignment based on the presence of a CurrentUser object, available from a Spring @AdviceController to all pages.

Notice the th:inline setting of “text”. We’ve done a lot of Thymeleaf inlining before, either in HTML or JavaScript. The advantage here is that the variables aren’t wrapped in quotes as they would be with th:inline=”javascript”.

With the above few lines of code we can now control where the tag cloud block is affixed on the sidebar based on whether the user is logged-in.

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.