FreeMarker Common Operations
Last updated: January 8, 2024
Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.
Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.
Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.
The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:
>> Become an efficient full-stack developer with Jmix
Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.
Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.
To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .
And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .
Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.
Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.
Write code that works the way you meant it to:
>> CodiumAI. Meaningful Code Tests for Busy Devs
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .
The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
>> Take a look at DBSchema
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:
>> Try out the Profiler
A quick guide to materially improve your tests with Junit 5:
Do JSON right with Jackson
Download the E-book
Get the most out of the Apache HTTP Client
Get Started with Apache Maven:
Working on getting your persistence layer right with Spring?
Explore the eBook
Building a REST API with Spring?
Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
>> REST With Spring (new)
Get started with Spring and Spring Boot, through the reference Learn Spring course:
>> LEARN SPRING
Looking for the ideal Linux distro for running modern Spring apps in the cloud?
Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.
This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.
Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:
>> Try Alpaquita Containers now.
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .
You can explore the course here:
>> Learn Spring Security
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .
Get started with Spring Data JPA through the guided reference course:
>> CHECK OUT THE COURSE
Get started with Spring Boot and with core Spring, through the Learn Spring course:
![](http://earnmoneybangla.online/777/templates/cheerup1/res/banner1.gif)
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.
In this tutorial, we’ll see what we can do out-of-the-box with FreeMarker, though note that it is quite configurable and even integrates nicely with Spring .
Let’s get started!
2. Quick Overview
To inject dynamic content in our pages, we need to use a syntax that FreeMarker understands :
- ${…} in the template will be replaced in the generated output with the actual value of the expression inside the curly brackets – we call this interpolation – a couple of examples are ${1 + 2 } and ${variableName}
- FTL tags are like HTML tags (but contain # or @ ) and FreeMarker interprets them, for example <#if…></#if>
- Comments in FreeMarker start with <#– and end with –>
3. The Include Tag
The FTL include directive is a way for us to follow the DRY principle in our application. We will define the repetitive content in a file and reuse it across different FreeMarker templates with single include tag.
One such use case is when we want to include the menu section inside many pages. First, we’ll define the menu section inside a file – we’ll call it menu.ftl – with the following content:
And on our HTML page, let’s include the created menu.ftl :
And we can also include FTL in our fragments, which is great.
4. Handling Value Existence
FTL will consider any null value as a missing value. Thus, we need to be extra careful and add logic to handle null inside our template.
We can use the ?? operator to check if an attribute, or nested property, exists. The result is a boolean:
So, we’ve tested the attribute for null, but that’s not always enough. Let’s now define a default value as a fallback for this missing value. To do this, we need the ! operator placed after the name of the variable:
Using round brackets, we can wrap many nested attributes.
For example, to check if the attribute exists and has a nested property with another nested property, we wrap everything:
Finally, putting everything together, we can embed these among static content:
And, if the student were null , we’d see:
Please notice the additional ?c directive used after the ?? . We did it to convert the boolean value to a human-readable string.
5. The If-Else Tag
Control structures are present in FreeMarker, and the traditional if-else is probably familiar:
While the elseif and else branches are optional, the conditions must resolve to a boolean value.
To help us with our evaluations, we’ll likely use one of:
- x == y to check is x is equal to y
- x != y to return true only if x differs from y
- x lt y means that x must be strictly smaller than y – we can also use < instead of lt
- x gt y evaluates to true only if x is strictly greater than y – we can use > instead of gt
- x lte y tests if x is less than or equal to y – the alternative to lte is <=
- x gte y tests if x is greater than or equal to y – the alternative of gte is >=
- x?? to check the existence of x
- sequence?seqContains(x) validates the existence of x inside a sequence
It’s very important to keep in mind that FreeMarker considers >= and > as closing characters for an FTL tag. The solution is to wrap their usage in parentheses or use gte or gt instead.
Putting it together, for the following template:
We end up with the resulting HTML code:
6. Containers of Sub-Variables
In FreeMarker, we have three types of containers for sub-variables:
- Hashes are a sequence of key-value pairs – the key must be unique inside the hash and we don’t have an ordering
- Sequences are lists where we have an index associated with each value – a noteworthy fact is that sub-variables can be of different types
- Collections are a special case of sequences where we can’t access the size or retrieve values by index – we can still iterate them with the list tag though!
6.1. Iterating Items
We can iterate over a container in two basic ways. The first one is where we iterate over each value and have logic happening for each of them:
Or, when we want to iterate a Hash , accessing both the key and the value:
The second form is more powerful because it also allows us to define the logic that should happen at various steps in the iteration:
The item represents the name of the looped variable, but we can rename it to what we want. The else branch is optional.
For a hands-on example, well define a template where we list some statuses:
This will return us the following HTML when our container is [“200 OK”, “404 Not Found”, “500 Internal Server Error”] :
6.2. Items Handling
A hash allows us two simple functions: keys to retrieve only the keys contained, and values to retrieve only the values.
A sequence is more complex; we can group the most useful functions:
- chunk and join to get a sub-sequence or combine two sequences
- reverse , sort, and sortBy for modifying the order of elements
- first and last will retrieve the first or last element, respectively
- size represents the number of elements in the sequence
- seqContains , seqIndexOf , or seqLastIndexOf to look for an element
7. Type Handling
FreeMarker comes with a huge variety of functions (built-ins) available for working with objects. Let’s see some frequently used functions.
7.1. String Handling
- url and urlPath will URL-escape the string, with the exception that urlPath will not escape slash /
- jString , jsString, and jsonString will apply the escaping rules for Java, Javascript and JSON, respectively
- capFirst , uncapFirst , upperCase , lowerCase and capitalize are useful for changing the case of our string, as implied by their names
- boolean , date , time , datetime and number are functions for converting from a string to other types
Let’s now use a few of those functions:
And the output for the template above will be:
When using the date function, we’ve also passed the pattern to use for parsing the String object. FreeMarker uses the local format unless specified otherwise , for example in the string function available for date objects.
7.2. Number Handling
- round , floor and ceiling can help with rounding numbers
- abs will return a number’s absolute value
- string will convert the number to a string. We can also pass four pre-defined number formats: computer , currency , number , or percent or define our own format, like [ “0.###” ]
Let’s do a chain of a few mathematical operations:
And as expected, the resulting value is 11.12.
7.3. Date Handling
- .now represents the current date-time
- date , time and datetime can return the date and time sections of the date-time object
- string will convert date-times to strings – we can also pass the desired format or use a pre-defined one
We’re going to now get the current time and format the output to a string containing only the hours and minutes:
The resulting HTML will be:
8. Exception Handling
We’ll see two ways to handle exceptions for a FreeMarker template.
The first way is to use attempt-recover tags to define what we should try to execute and a block of code that should execute in case of error.
The syntax is:
Both attempt and recover tags are mandatory. In case of an error, it rolls back the attempted block and will execute only the code in the recover section .
Keeping this syntax in mind, let’s define our template as:
When attributeWithPossibleValue is missing, we’ll see:
And the output when attributeWithPossibleValue exists is:
The second way is to configure FreeMarker what should happen in case of exceptions.
With Spring Boot, we easily configure this via properties file; here are some available configurations:
- spring.freemarker.setting.template_exception_handler=rethrow re-throws the exception
- spring.freemarker.setting.template_exception_handler=debug outputs the stack trace information to the client and then re-throws the exception.
- spring.freemarker.setting.template_exception_handler=html_debug outputs the stack trace information to the client, formatting it so it will be usually well readable in the browser, and then re-throws the exception.
- spring.freemarker.setting.template_exception_handler=ignore skips the failing instructions, letting the template continue executing.
- spring.freemarker.setting.template_exception_handler=default
9. Calling Methods
Sometimes we want to call Java methods from our FreeMarker templates. We’ll now see how to do it.
9.1. Static Members
To start accessing static members, we could either update our global FreeMarker configuration or add a S taticModels type attribute on the model, under the attribute name statics :
Accessing static elements is straight-forward.
First, we import the static elements of our class using the assign tag, then decide on a name and, finally, the Java classpath.
Here’s how we’ll import Math class in our template, show the value of the static PI field, and use the static pow method:
The resulting HTML is:
9.2. Bean Members
Bean members are very easy to access: use the dot (.) and that’s it!
For our next example, we will add a Random object to our model:
In our FreeMarker template, let’s generate a random number:
This will cause output similar to:
9.3. Custom Methods
The first step for adding a custom method is to have a class that implements FreeMarker’s TemplateMethodModelEx interface and defines our logic inside the exec method:
We’ll add an instance of our new class as an attribute on the model:
The next step is to use our new method inside our template:
Finally, the resulting output is:
10. Conclusion
In this article, we’ve seen how to use the FreeMarker template engine inside our project. We’ve focused on common operations, how to manipulate different objects, and a few more advanced topics.
The implementation of all these snippets is available over on GitHub .
Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:
>> Spring Boot Application on Liberica Runtime Container.
Slow MySQL query performance is all too common. Of course it is.
The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.
Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:
Basically, write code that works the way you meant it to.
![freemarker conditional assignment Build your API with SPRING - book cover](https://www.baeldung.com/wp-content/uploads/2016/05/baeldung-rest-post-footer-main-1.2.0.jpg)
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 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.
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.
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 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 next example produces a list of cars.
We have a Car bean. It has two attributes: name and price.
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> directive creates a new name variable. The value of the variable is printed with the ${name} syntax.
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 <#compress> directive removes superfluous white-space when we use a white-space insensitive format (e.g. HTML or XML)
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 hello.ftlh template file; it refers to the name variable which was passed with the ModelAndView object.
![](http://earnmoneybangla.online/777/templates/cheerup1/res/banner1.gif)
Spring Boot FreeMarker
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.
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.
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 .
Page Contents
Description
- 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> . Note that this string literal does not expand interpolations (as "${foo}" ).
- value : the value to store. Expression.
- namespacehash : a hash that was created for a namespace (by import ). Expression.
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
Example: variable seasons will store a sequence:
IMAGES
VIDEO
COMMENTS
Note: When you want to test if x > 0 or x >= 0, writing <#if x > 0> and <#if x >= 0> is WRONG, as the first > will close the #if tag. To work that around, write <#if x gt 0> or <#if gte 0>.Also note that if the comparison occurs inside parentheses, you will have no such problem, like <#if foo.bar(x > 0)> works as expected.
That can have a non-string result and lazy-evaluates its parameters. In FreeMarker you can approach this as a boolean formatting task: [@printForm (myForm.id == 0)?string('add', 'change') /] Update: Here's a full working example: This does seem to work in a non freemarker scope, but when you use it as a parameter to a macro it doesn't work ...
In freemarker, can you assign a boolean value like this: [#if something = value] [#assign bool = true] [/#if] To then be used in a conditional statement like this: [#if bool] ...do something. [/#if] So far I have not been successful doing this in this format, but thought I might be missing something.
When you supply value for interpolations: The usage of interpolations is ${ expression } where expression gives the value you want to insert into the output as text. So ${(5 + 8)/2} prints "6.5" to the output (or possibly "6,5" if the language of your output is not US English). When you supply a value for the directive parameter: You have ...
FreeMarker Manual -- For FreeMarker 2.3.20 HTML generated: 2013-06-27 20:54:33 GMT ...
The c built-in supports booleans since FreeMarker 2.3.20. This built-in converts a boolean to a "computer language" literal, as opposed to format it for human reading. This formats is independent of the boolean_format configuration setting, as that setting is meant to specify the format for human readers. Instead, it depends on the c_format ...
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 ...
When setting up a conditional statement you must begin by assigning a variable for any fields you want to reference using the #assign Freemarker Tag. At this point, the values for those variables are checked, a condition is included to account for edge cases, and the conditional statement is closed out.
spring.freemarker.setting.template_exception_handler=html_debug outputs the stack trace information to the client, formatting it so it will be usually well readable in the browser, and then re-throws the exception. spring.freemarker.setting.template_exception_handler=ignore skips the failing instructions, letting the template continue executing.
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>, <# ...
Conditional statements FreeMarker supports conditional logic such as if, else, and elseif to control the flow of template execution based on certain conditions.
It can also be one of the assignment shorthand operators (since FreeMarker 2.3.23): ++, -- , +=, -= , *=, /= or %=. Like <#assign. x++> is similar to <#assign x = x +. 1>, and <#assign x += 2> is the same as <#assign x = x + 2> . Note that ++ always means arithmetical addition (an so it will fail on non-numbers), unlike + or += that are ...
If you know what namespaces are: assign directive creates variables in namespaces. Normally it creates the variable in the current namespace (i.e. in the namespace associated with the template where the tag is). However, if you use ... FreeMarker Manual -- For FreeMarker 2.3.20
A few highlights of FreeMarker: Powerful template language: Conditional blocks, iterations, assignments, string and arithmetic operations and formatting, macros and functions, including other templates, escaping by default (optional), and many more
For example, to pass conditionally different values as an argument for a constructor of a field or a base class, it is impossible to use a plain if-else statement; in this case we can use a conditional assignment expression, or a function call. Bear in mind also that some types allow initialization, but do not allow assignment, or even that the ...
Comparing Variables in FreeMarker: getDataType Function. FreeMarker is a popular templating engine that is used to generate dynamic web pages. It is a powerful tool that allows developers to separate the presentation logic from the business logic. One of the most common tasks when working with variables in FreeMarker is to determine their data ...
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 ...
2. That example should work equally well with #assign and #global. You had some kind of oversight there. As of #assign VS #global: Variables set via #assign are only visible from the template where they were assigned, plus in the templates that where #include -d in that template (or #include -d in an #include -d template, etc.), because # ...
This built-in splits a sequence into multiple sequences of the size given with the 1st parameter to the built-in (like mySeq?chunk(3) ). The result is the sequence of these sequences. The last sequence is possibly shorter than the given size, unless the 2nd parameter is given (like mySeq?chunk(3, '-') ), that is the item used to make up the ...