Thymeleaf
variable check
Java templating
conditional rendering
web development

Thymeleaf check if a variable is defined

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Thymeleaf templates, checking whether a variable exists helps prevent rendering errors and keeps views resilient across optional data scenarios. The safest pattern is to check for presence and nullability before dereferencing nested properties. This is especially important when templates are reused across different controller paths with different model attributes.

Core Sections

Basic presence and null checks

For model attributes, you can guard rendering with th:if and a null check.

html
<div th:if="${user != null}">
  <span th:text="${user.name}">name</span>
</div>

This protects nested access when attribute is missing or null.

Check whether variable exists in context

Thymeleaf provides context utilities to test variable presence directly.

html
<div th:if="${#ctx.containsVariable('user')}">
  <span th:text="${user.name}">name</span>
</div>

Use this when you need to distinguish missing variable from variable present but null.

Safe fallback rendering

Provide fallback UI when optional values are absent.

html
<span th:text="${user != null ? user.name : 'Guest'}">Guest</span>

Fallbacks improve user experience and avoid empty placeholders.

Nested property access strategy

If user may be missing, avoid directly rendering deep chains like user.address.city without guards. Wrap nested sections in one parent condition so child expressions remain safe.

html
<section th:if="${user != null and user.address != null}">
  <span th:text="${user.address.city}">city</span>
</section>

Grouping conditions keeps templates readable and predictable.

Controller and model consistency

The most maintainable approach is predictable model contracts. Controllers should set expected attributes explicitly, even if values are null or defaults. When templates depend on optional objects, document expected model keys in code comments or team template guidelines.

In larger projects, shared fragments often fail because one controller path misses an attribute. Adding model setup helpers reduces these mismatches and decreases repetitive null guards in templates.

Testing template conditions

Template tests can verify both presence and absence paths.

java
model.addAttribute("user", null);
// render template and assert fallback text appears

These tests catch regressions when controllers or fragments are refactored.

Fragment design for optional models

Reusable fragments benefit from explicit input contracts. When creating a Thymeleaf fragment that expects optional variables, include defensive checks in the fragment itself instead of assuming callers always pass complete models.

html
1<div th:fragment="userCard(user)">
2  <h3 th:text="${user != null ? user.name : 'Unknown user'}">Unknown user</h3>
3  <p th:if="${user != null and user.email != null}" th:text="${user.email}">email</p>
4</div>

Caller template:

html
<div th:replace="~{fragments/user :: userCard(${user})}"></div>

This keeps fragment behavior stable even when some controller paths provide partial data.

For larger templates, prefer small boolean helper variables set with th:with so conditions stay readable. Long inline expressions are hard to maintain and easy to misread in reviews. Readable condition blocks reduce production rendering errors and improve onboarding for new contributors.

A practical review rule is to reject templates that dereference optional model attributes without a guard block. This single rule prevents most runtime rendering failures in mixed-controller applications.

When possible, keep optional-view logic in small fragments so null checks are localized and easier to maintain.

Common Pitfalls

  • Accessing nested properties without checking parent object presence.
  • Assuming all controllers populate the same model attributes.
  • Confusing variable existence checks with non-null value checks.
  • Overusing complex inline conditions and reducing template readability.
  • Failing to test fallback rendering paths in template tests.

Summary

  • Use th:if and context checks to guard optional variables.
  • Distinguish between missing variables and null values when needed.
  • Apply fallback text for better resilience and user experience.
  • Keep controller model contracts explicit to reduce template fragility.
  • Add tests for both populated and missing-variable rendering paths.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.