Of course! Using the if directive in Java with FreeMarker is a fundamental skill for creating dynamic templates. Here’s a comprehensive guide covering the basics, common scenarios, and best practices.

The Basic if Directive
The most common structure is if-else.
Template Syntax:
<#if condition> <!-- This content is rendered if the condition is true --> <#else> <!-- This content is rendered if the condition is false --> </#if>
Key Points:
<#if>: Starts the conditional block.condition: An expression that evaluates to a boolean (trueorfalse).<#else>: Optional. Defines an alternative block to render if the condition is false.</#if>: Closes the conditional block.
Example: Java Data Model and Template
Let's see a complete, runnable example.

Java Code (Setting up the Data Model)
This Java code creates a Map of data that will be passed to the FreeMarker template.
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerIfExample {
public static void main(String[] args) throws IOException, TemplateException {
// 1. Create a FreeMarker configuration
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
// Specify the folder where your FreeMarker templates are located
cfg.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
// 2. Create the data model (the "Model" in MVC)
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("user", "Alex");
dataModel.putisLoggedIn(true);
dataModel.put("userRole", "admin");
dataModel.put("itemCount", 5);
dataModel.put("welcomeMessage", "Welcome to our site!");
// 3. Load the template
Template template = cfg.getTemplate("if_example.ftl");
// 4. Process the template and write the output to a file
try (Writer out = new FileWriter("output.html")) {
template.process(dataModel, out);
System.out.println("Template processed successfully. Check output.html");
}
}
}
FreeMarker Template (if_example.ftl)
This template uses the data from the Java code to make decisions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">FreeMarker If Example</title>
<style>body { font-family: sans-serif; margin: 2em; } .admin { color: blue; } .guest { color: gray; } </style>
</head>
<body>
<h1>Hello, ${user}!</h1>
<!-- Example 1: Simple boolean check -->
<#if isLoggedIn>
<p>You are currently logged in.</p>
<#else>
<p>Please <a href="/login">log in</a>.</p>
</#if>
<hr>
<!-- Example 2: Using 'elseif' -->
<#if userRole == "admin">
<p class="admin">Welcome, Administrator! You have full access.</p>
<#elseif userRole == "editor">
<p>Welcome, Editor! You can modify content.</p>
<#else>
<p class="guest">Welcome, standard user.</p>
</#if>
<hr>
<!-- Example 3: Numeric comparison -->
<#if itemCount != 0>
<p>You have ${itemCount} items in your cart.</p>
<#else>
<p>Your cart is empty.</p>
</#if>
<hr>
<!-- Example 4: Checking if a variable exists (is not null) -->
<#if welcomeMessage??>
<p>${welcomeMessage}</p>
<#else>
<p>No message is set for you.</p>
</#if>
<hr>
<!-- Example 5: Checking if a string is empty -->
<#if !user?has_content>
<p>The user name is not set.</p>
<#else>
<p>User name is set to: '${user}'</p>
</#if>
</body>
</html>
Generated HTML (output.html)
When you run the Java code, this is the HTML that will be generated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">FreeMarker If Example</title>
<style>body { font-family: sans-serif; margin: 2em; } .admin { color: blue; } .guest { color: gray; } </style>
</head>
<body>
<h1>Hello, Alex!</h1>
<!-- Example 1: Simple boolean check -->
<p>You are currently logged in.</p>
<hr>
<!-- Example 2: Using 'elseif' -->
<p class="admin">Welcome, Administrator! You have full access.</p>
<hr>
<!-- Example 3: Numeric comparison -->
<p>You have 5 items in your cart.</p>
<hr>
<!-- Example 4: Checking if a variable exists (is not null) -->
<p>Welcome to our site!</p>
<hr>
<!-- Example 5: Checking if a string is empty -->
<p>User name is set to: 'Alex'</p>
</body>
</html>
if Directive Variations and Features
a) elseif for Multiple Conditions
For more than two possibilities, use <#elseif>.

<#if temperature > 30> <p>It's a hot day!</p> <#elseif temperature > 20> <p>It's a pleasant day.</p> <#else> <p>It's a bit chilly.</p> </#if>
b) Checking for Existence with
The operator is crucial for avoiding errors when a variable might be null.
variable??returnstrueif the variable exists and is notnull.variable??returnsfalseif the variable isnullor does not exist.
<#if currentUser?? && currentUser.role == "admin"> <p>Show admin dashboard.</p> </#if>
c) Checking String Content with ?has_content
This is the best way to check if a string is null or empty ().
string?has_contentreturnstrueif the string is notnulland has a length greater than 0.- It returns
falseotherwise.
<#if name?has_content>
<p>Hello, ${name}!</p>
<#else>
<p>Hello, Guest!</p>
</#if>
d) Logical Operators (&&, , )
You can combine conditions using standard logical operators.
<#if (isLoggedIn && userRole == "admin") || (isLoggedIn && userRole == "editor")> <p>You have editing privileges.</p> </#if> <#if !isLoggedIn> <p>You must be logged in to perform this action.</p> </#if>
e) Parentheses for Grouping
Just like in mathematics, use parentheses to control the order of evaluation.
<#if (isLoggedIn && userRole == "admin") || (isSuperUser && !isLoggedIn)> <p>Access granted.</p> </#if>
Best Practices
- Always Check for
null: Unless you are 100% certain a variable will never benull, use the operator or?has_contentto preventNullPointerExceptions from breaking your template processing. - Use
?has_contentfor Strings: It's more readable and safer thanmyString?? && myString != "". - Keep Logic Simple: If your
ifstatement becomes too complex, consider moving the logic into your Java data model. Pass a pre-computed boolean flag to the template. This keeps your templates clean and focused on presentation.- Good in Java:
boolean canEdit = (isLoggedIn && "admin".equals(userRole)) || isSuperUser; dataModel.put("canEdit", canEdit); - Good in Template:
<#if canEdit> <button>Edit</button> </#if>
- Good in Java:
