conditional statement in freemarker template: if elseif else

Java code to set up model, template if.ftl.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

last modified January 27, 2024

This is an introductory tutorial of the FreeMarker Java template engine. We introduce the FreeMarker template engine and create several console and web applications. Maven is used to build our examples. NetBeans is used to manage the applications.

Table of contents

FreeMarker is a template engine for the Java programming language. Templates are written in the FreeMarker Template Language (FTL).

FreeMarker template engine

A template engine combines static data with dynamic data to produce content. A template is an intermediate representation of the content; it specifies how the output will be generated.

The advantages of a template engine are:

  • separation of concerns,
  • avoiding repetition of code,
  • easier switching between views,
  • reusability.

A FreeMarker template file has by convention a .ftl extension.

FreeMarker is not restricted to templates for HTML pages; it can be used to generate e-mails, configuration files, source code etc.

We use this FreeMarker dependency in a Gradle project.

FreeMarker interpolations

Interpolations are expressions put between the ${ } characters. FreeMarker will replace an interpolation in the output with the actual value of the expression inside the curly brackets.

In the following example, we use a FreeMarker template file to generate simple text output.

The example prints a simple text to the console. The final text was processed by a template engine.

Configuration is used to set the FreeMarker settings; it takes the version of the FreeMarker library as a parameter.

The setClassForTemplateLoading sets the class whose method will be used to load templates. The templates are located in the views subdirectory of src/main/resources directory.

With the getTemplate method, we retrieve the test.ftlh template file.

The data model is created. The data from the model will be dynamically placed into the FreeMarker template file.

The process method executes the template, using the provided data model and writing the generated output to the supplied writer.

The test.ftlh template file contains one interpolation; it will be replaced with the generated string.

This is the Gradle build file.

FreeMarker list directive

The #list directive lists a collection of data.

The next example produces a list of cars.

We have a Car bean. It has two attributes: name and price.

This example is a Java console program, which uses FreeMarker to dynamically create a text output containing a list of cars.

Here we create a list of Car objects and put it into the data model.

The template file contains a #list directive which prints the attributes of the car objects; the attributes are accessed with the dot character.

FreeMarker directives

FreeMarker directives are special tags that perform an action. There are two kinds of directives: built-in and custom.

The <#assign> tag creates a new plain variable. It can be accessed with the ${} construct. The variable is created in the template. If there is an equally named variable in the data model, the template variable hides it.

The <#assign> directive creates a new name variable. The value of the variable is printed with the ${name} syntax.

The example prints this line.

Conditional processing of template sections can be done with he <#if> , <#elseif> , and <#else> directives.

The example creates a new value variable and uses conditional directives to test the value.

The <#list> directive is used for traversing a sequence.

In the example, we assing a new sequence of colour names to the colours variable. The <#list> directive goes through the collection and prints each item.

The example gives this output.

In this example, we create a hash variable and use the <#list> to output the values and the keys of the hash.

The <#compress> directive removes superfluous white-space when we use a white-space insensitive format (e.g. HTML or XML)

We have text with spaces, tabs, and new lines.

The program removed all superfluous white-space.

FreeMarker with Spark

In the following example, we are going to integrate the FreeMarker template engine into our Spark application.

This is the directory structure of the project.

Here we have the Gradle build file, which includes the spark-template-freemarker dependency.

We set up the same application for FreeMarker.

We configure FreeMarker with the Configuration class. The template files are going to be placed into the views directory, which must be located on the classpath.

The FreeMarkerEngine is passed to the get method.

This is the hello.ftlh template file; it refers to the name variable which was passed with the ModelAndView object.

Spring Boot FreeMarker

In the next application, we integrate FreeMarker into a Spring Boot web application.

This is the project structure.

This is the Gradle build file. It includes dependencies for Spring Boot and FreeMarker. There is no need to configure the FreeMarker in Spring Boot. Upon finding the FreeMarker dependency in the POM file, Spring Boot automatically takes care of the configuration.

The Application sets up the Spring Boot application. The @SpringBootApplication annotation defines the class as a configuration class,enables auto-configuration, and enables component scanning.

This is the controller class for the Spring Boot web application. The controller has two mappings. The first mapping resolves to the index.ftl file and the second mapping to the hello.ftlh file.

This is the index.ftlh file. It has an HTML form which sends a message to the server.

The server responds with a message back to the client. The response is created from the hello.ftlh template file.

The Spring Boot starts an embedded Tomcat server, listening on port 8080.

Java FreeMarker manual

In this tutorial we have worked with the FreeMarker template engine.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials .

Using FreeMarker templates (FTL)- Tutorial

1. introduction to freemarker, 2. installation of freemarker, 3. eclipse integration, 4. basic example, 5.1. reuse common template fragments, 5.2. variables, 5.3. if then else, 5.4. handling null/undefined values, 5.5. escape, 6.1. freemarker homepage.

FreeMarker Tutorial. This tutorial explains how can you define FreeMarker templates and how can you generate output based on these templates. It also demonstrates the usage of macros.

FreeMarker is a Java-based template engine which can be used in stand-alone or servlet-based Java programs.

In FreeMarker you define templates, which are text files that contain the desired output, except that they contain placeholders like ${name} , and even some logic like conditionals, loops, etc. In your Java program you supply the actual values for these placeholders and the final output is generated based on this input.

The input of templates is a bunch of named variables that you usually provide as a Map<String, Object> (the Map entries will be the variables) or as a JavaBean (the JavaBean properties will be the variables). The variable values can be simple strings, numbers and such primitive values, but also lists, maps, or arbitrary Java objects whose methods you can call from the template. Note that when accessing JavaBean properties, myObject.myProperty syntax should be used instead of myObject.getMyProperty() .

The output of templates is written into a Writer that you provide, so it can go into a HTTP response (for dynamic web pages), into a local file, into a String , etc.

It is configurable from where FreeMarker reads the templates; commonly used options are loading from a file-system directory, from the class-path, from the servlet context ( WEB-INF/templates or such), or even from a database table. It’s also possible to "load" templates directly from String objects.

To use FreeMarker download the latest version of it from the following webpage and add it to the classpath of your Java project.

FreeMarker code completion and syntax highlighting is part of the JBoss Tools . Add the following update site to your Eclipse installation via Help   Install New Software…​

Add the JBoss Tools update site and search for FreeMarker

Create a new Java project called com.vogella.freemarker.first . Create a new folder called lib and add the Freemarker library to it. Add this library to the classpath for your project.

If you don’t know how to achieve that, please see the Eclipse IDE Tutorial for instructions on the required steps.

Create a new folder called templates inside the folder of the com.vogella.freemarker.first package. Inside that, create the following file with name helloworld.ftl .

Create the following class which demonstrates the usage of Java objects in templates.

Create the following class which creates the input for this template and creates the output.

5. Useful FTL tricks

When you find yourself copy-pasting common parts between templates a lot, you should probably use macros.

Continuing our last example, create a new folder called lib inside the templates directory, and there create a file called utils.ftl , with this content:

Now you can simplify helloworld.ftl like this:

Another way of reusing template fragments is moving the common fragment into its own ftl file. Then just insert it with <#include "lib/myfragment.ftl"> . This is less flexible than macros, but simpler in concept: it mimics copy-pasting.

You can define and assign content to variables inside the FTL files for easy reuse.

` You can handle if / else cases, see below for an example.

FreeMarker requires you to provide an explicit default for variables, so avoid values that are null or undefined:

When generating HTML, it’s important to escape < , & , etc. in values that were not meant to store HTML and can contain these problematic characters. You can apply such escaping like ${message?html} . You can also ask FreeMarker to add ?html to all ${} -s in a section like this:

It’s important to understand that #escape only affects the ${} bits that are inside the enclosed section in the template file when you look at it in a text editor. That means, ${} embracements which are in other templates or macros called from there, won’t be affected.

6. Links and Literature

FreeMarker homepage

If you need more assistance we offer Online Training and Onsite training as well as consulting

See License for license information .

freemarker assign conditional

freemarker assign conditional

What's new in Outlook 2024 for Windows

Start your article with a very short introduction (1 sentence). Put yourself in the reader's place - why are they here? What should they do?

Get straight to a quick list of steps to accomplish the task.

If you need to explain a concept, or they have to do pre-requisite steps, add a quick summary below the step where they need it, and link to the concept or steps.

Keep procedures short - preferably 5 or fewer steps, no more than 8.

Use Ui style for user interface elements or for text people need to enter.

Use the verbs choose, select, or enter as actions, and format menus as Menu > Command .

Optionally, add a screenshot for context (if UI is hard to locate, or it’s needed to complete the task).

Maximum width: 520 pixels. Use a standard theme, do not show any personal information, and crop to show only what's relevant.

Expanded form of file card

If you want to add a video or screenshot, use a two-column grid and have the steps in the left and the video or screenshot in the right - see Steps and video grid example .

Target no more than 500 words for an article.

Example article

Change my photo

Facebook

Need more help?

Want more options.

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

freemarker assign conditional

Microsoft 365 subscription benefits

freemarker assign conditional

Microsoft 365 training

freemarker assign conditional

Microsoft security

freemarker assign conditional

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

freemarker assign conditional

Ask the Microsoft Community

freemarker assign conditional

Microsoft Tech Community

freemarker assign conditional

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

FreeMarker

  • Report a Bug
  • Apache FreeMarker Manual
  • Template Author's Guide
  • Miscellaneous

Defining variables in the template

  • Alpha. index
  • Expressions
  • #directives

Most of the variables that a typical template works with comes from the data-model. But templates can also define variables themselves, usually to hold loops variables, temporary results, macros, etc. Such variables are outside the data-model; modifying the data-model from templates is by design unsupported. Note that each template processing job has its own private set of these variables, which will be thrown away when the template processing job is finished.

You access variables defined in the template the same way as you access variables defined in the data-model root. For example, if you create a variable called "foo" in the template, you can print its value with ${foo} . If, coincidently, there's a variable called "foo" in the data-model too, the variable created in the template will hide (not overwrite!) it.

There are these kinds of variables that are defined in a template:

"plain" variables : They are accessible from everywhere in the template, or from another templates that was inserted with the include directive . You can create and replace these variables with the assign directive , or, because macros and functions are just variables, with the macro directives and function directives .

Local variables : They can only be set inside a macro definition body or function definition body , and are only visible from there, not from other macros or functions called from there. A local variable only exists for the duration of a macro or function call. You can create and replace local variables inside the definition body with the local directive . Macro and function parameters are also local variables.

Loop variables : Loop variables are created automatically by directives like list (like x in <#list xs as x> ... </#list> ), and they only exist between the start-tag and end-tag of the directive. (User defined directives, like macros, can also create loop variables.) They are only visible directly between these tags, not from macros or functions called from there. As such, they are quite similar to local variables, but they can't be assigned to directly.

Global variables : These should be seldom used. Global variables are shared by all templates, even if they belong to different name spaces because of import -ing . Thus, their visibility is similar to data-model variables. They are set via the global directive . Global variables hide (but don't overwrite) the data-model variables of the same name.

Example: Create and replace variables with assign :

In the next example we demonstrate that local variables hide (not overwrite) "plain" variables of the same name, and that loop variables hide (not overwrite) local and "plain" variables of the same name:

In the next example we demonstrate that an inner loop variable can hide (not overwrite) an outer loop variable of the same name:

When a variable hides the variable from the data-model, you can still read that variable from the data-model using special variable globals . For example, assume we have a variable called user in the data-model with value "Big Joe":

You could also write .data_model.user instead, and then not even a <#global user = " ... "> can hide the value in the data-model. However, global variables are often purposely set to override the value coming from the data-model, so using globals is a better practice usually.

For information about syntax of variables (allowed characters and such) please read: The Template/Expressions

  • What is FreeMarker?
  • Version history
  • Privacy policy

Often used / Reference

  • Try template online
  • Expressions cheatsheet
  • .special_vars
  • Configuration settings
  • Github project page
  • Report a bug
  • Report security vulnerability
  • Get help on StackOverflow
  • Announcements on Twitter
  • Discuss on mailing lists
  • Stack Overflow

Last generated: 2024-02-12 20:34:04 GMT , for Freemarker 2.3.32

© 1999 –2024 The Apache Software Foundation . Apache FreeMarker, FreeMarker, Apache Incubator, Apache, the Apache FreeMarker logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.

IMAGES

  1. FreeMarker: Conditional Statements

    freemarker assign conditional

  2. Introduction to FreeMarker Template (FTL). FTL Tutorial

    freemarker assign conditional

  3. Introduction and use of freemarker

    freemarker assign conditional

  4. Using FreeMarker with servlets

    freemarker assign conditional

  5. FreeMarker Tutorial for Beginners

    freemarker assign conditional

  6. Introduction and use of freemarker

    freemarker assign conditional

VIDEO

  1. Assign a Color to Max Sales in Column Chart

  2. Lesson 12: Conditional Type II (Improbable / Unlikely )Condition

  3. CASE Statement for Conditional Logic in SQL

  4. Conditional Sentence| How if is used in various situation? Question asked frequently in NDA exam

  5. Form Conditional Logic Upgrades Live!

  6. Cách để tạo Project Hibernate với NetBeans bản mới nhất & generate entity từ DB sử dụng SQL Server

COMMENTS

  1. if, else, elseif

    Description You can use if, elseif and else directives to conditionally skip a section of the template. The condition -s must evaluate to a boolean value, or else an error will abort template processing. The elseif -s and else -s must occur inside if (that is, between the if start-tag and end-tag).

  2. FreeMarker: Conditional Statements

    FreeMarker: Conditional Statements A Conditional statement allows you to dynamically determine which content will display in an email for a recipient based on information stored in CRM. For example, you can display specific content in an email template based on the recipient's gender.

  3. assign

    Description With this you can create a new variable, or replace an existing variable. Note that only top-level variables can be created/replaced (i.e. you can't create/replace some_hash.subvar, but some_hash ). For more information about variables, read this: Template Author's Guide/Miscellaneous/Defining variables in the template Note:

  4. Expressions

    Expressions. When you supply values for interpolations or directive parameters you can use variables or more complex expressions. For example, if x is the number 8 and y is 5, the value of (x + y)/2 resolves to the numerical value 6.5. Before we go into details, let's see some concrete examples:

  5. java

    3 Answers Sorted by: 41 Yes, you can write: <#if hot> it's hot <#else> it's not </#if> And if you're doing lots of freemarker, I really can recommend IntelliJ IDEA 8, its freemarker support really helps... Share Improve this answer Follow edited May 3, 2012 at 4:53 answered Nov 17, 2008 at 19:42 Ulf Lindback 14.1k 3 43 31 Add a comment 19

  6. boolean assignment in freemarker using conditional statements

    1 Answer Sorted by: 1 You haven't included the error message... but I guess your problem is that if the first condition is false, then you never assign to the bool variable, so it won't exist at all, and so you can't use it in the second expression. To fix that, the first #if could to be changed to: [#assign bool = something == value] Share

  7. FreeMarker Manual

    Description You can use if, elseif and else directives to conditionally skip a section of the template. The condition -s must evaluate to a boolean value, or else an error will abort template processing. The elseif -s and else -s must occur inside if (that is, between the if start-tag and end-tag).

  8. FreeMarker Manual

    Description Synopsis <#assign <#assign <#assign ><#assign </#assign><#assign </#assign> Where: name: name of the variable. It is not expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example <#assign "foo-bar" = 1>.

  9. conditional statement in freemarker template: if elseif else

    template if.ftl if elseif else n=${n} <#if n > 1> n is greater than 1 <#if n==1> n is equal to 1 <#elseif n==2> n is equal to 2 <#else> n is greater than 2 </#if ...

  10. FreeMarker Common Operations

    1. Introduction FreeMarker is a template engine, written in Java, and maintained by the Apache Foundation. We can use the FreeMarker Template Language, also known as FTL, to generate many text-based formats like web pages, email, or XML files.

  11. Basics of Personalization in MessageGears (Using Freemarker)

    Condition Statements are a powerful part of the FreeMarker templating language. Conditional Statements are used to handle content that should only display if one or more conditions are met. ... Variables are established in FreeMarker using the Assign tag. Assigning variables can be done within one line of code, or broken into multiple lines to ...

  12. Java FreeMarker

    FreeMarker is a template engine for the Java programming language. Templates are written in the FreeMarker Template Language (FTL). ... The <#assign> tag creates a new plain variable. It can be accessed with the ${} construct. The variable is created in the template. ... Conditional processing of template sections can be done with he <#if>, <# ...

  13. list, else, items, sep, break, continue

    Skipping items conditionally Nesting loops into each other Treatment of missing (null) elements Notes for Java programmers Synopsis The simplest form for listing a sequence (or collection) is: <#list sequence as item > Part repeated for each item </#list> and to list the key-value pairs of a hash (since 2.3.25):

  14. Freemarker cheat sheet

    5 Hashes. Hashes are defined as key/value pairs similar to those of a map. Each key contains a single value, which can be any of the above (number, string, boolean...). The key must be written between quotation marks and followed by a colon and its value. Each key/value pair will be separated from the others by a comma.

  15. Using FreeMarker templates (FTL)- Tutorial

    1. Introduction to FreeMarker FreeMarker is a Java-based template engine which can be used in stand-alone or servlet-based Java programs. In FreeMarker you define templates, which are text files that contain the desired output, except that they contain placeholders like $ {name}, and even some logic like conditionals, loops, etc.

  16. The template at a glance

    With the if directive you can conditionally skip a section of the template. For example, assume that in the very first example you want to greet your boss, Big Joe, differently than other users: Template

  17. What's new in Outlook 2024 for Windows

    Use Ui style for user interface elements or for text people need to enter. Use the verbs choose, select, or enter as actions, and format menus as Menu > Command. Optionally, add a screenshot for context (if UI is hard to locate, or it's needed to complete the task). Maximum width: 520 pixels. Use a standard theme, do not show any personal ...

  18. Built-ins for booleans

    You can use it in two ways: As foo?string ("yes", "no"): Formats the boolean value to the first parameter (here: "yes") if the boolean is true, and to the second parameter (here: "no") if it's false.

  19. freemarker

    1 I am currently looking to figure the scope of #assign variable. However, scope seems to be confusing please see following example and try to explain. I have some hypothesis which works but if somebody has concrete documentation, it will be very helpful.

  20. Defining variables in the template

    Example: Create and replace variables with assign: Template <#assign x = 1> <#-- create variable x --> $ {x} <#assign x = 2> <#-- replace variable x --> $ {x} <#assign x++> <#-- replace variable x --> $ {x} Output 1 2 3

  21. Testing variable of boolean type in Freemarker

    8 The isOffline field in my websetting object is a boolean type. In my Freemarker template, I need to check if it's true of false. So I did the following, but it does not work <#if !websetting.isOffline> false </#if> It looks like Freemarker does not support the Not !.