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 .

ftl assign map

  • Documentation
  • GeoServer 2.25.x User Manual »
  • Tutorials »
  • Freemarker Templates

Freemarker Templates ¶

Introduction ¶.

This tutorial will introduce you to a more in depth view of what FreeMarker templates are and how you can use the data provided to templates by GeoServer.

Freemarker is a simple yet powerful template engine that GeoServer uses to allow user customization of outputs. In particular, at the time of writing it’s used to allow customization of GetFeatureInfo, GeoRSS and KML outputs.

Freemarker allows for simple variable expansions, as in ${myVarName} , expansion of nested properties, such as in ${feature.myAtt.value} , up to little programs using loops, ifs and variables. Most of the relevant information about how to approach template writing is included in the Freemarker’s Designer guide and won’t be repeated here: the guide, along with the KML Placemark Templates and GetFeatureInfo Templates tutorials should be good enough to give you a good grip on how a template is built.

Template Lookup ¶

GeoServer looks up templates in three different places, allowing for various levels of customization. For example given the content.ftl template used to generate WMS GetFeatureInfo content:

Look into GEOSERVER_DATA_DIR/workspaces/<workspace>/<datastore>/<featuretype>/content.ftl to see if there is a feature type specific template

Look into GEOSERVER_DATA_DIR/workspaces/<workspace>/<datastore>/content.ftl to see if there is a store specific template

Look into GEOSERVER_DATA_DIR/workspaces/<workspace>/content.ftl to see if there is a workspace specific template

Look into GEOSERVER_DATA_DIR/workspaces/content.ftl looking for a global override

Look into GEOSERVER_DATA_DIR/templates/content.ftl looking for a global override

Look into the GeoServer classpath and load the default template

Each templated output format tutorial should provide you with the template names, and state whether the templates can be type specific, or not. If you can’t find the source files for the default template, look in the service jar of the geoserver distribution (for example, wms-x.y.z.jar). You just have to unzip it, and you’ll find the xxx.ftl files GeoServer is using as the default templates.

Common Data Models ¶

Freemarker calls “data model” the set of data provided to the template. Each output format used by GeoServer will inject a different data model according to the information it’s managing. There are three very common elements that appear in almost every template: Feature, FeatureType and FeatureCollection. Here we provide a data model of each.

The data model is a sort of tree, where each element has a name and a type. Besides basic types, we’ll use:

list: a flat list of items that you can scan thru using the FreeMarker <#list> directive;

map: a key/value map, that you usually access using the dot notation, as in ${myMap.myKey }, and can be nested;

listMap: a special construct that is, at the same time, a Map, and a list of the values.

Here are the data models (as you can see there are redundancies, in particular in attributes, we chose this approach to make template building easier):

FeatureType (map)

name (string): the type name

attributes (listMap): the type attributes

name (string): attribute name

namespace (string): attribute namespace URI

prefix (string): attribute namespace prefix

type (string): attribute type, the fully qualified Java class name

isGeometry (boolean): true if the attribute is geometric, false otherwise

Feature (map)

fid (string): the feature ID (WFS feature id)

typeName (string): the type name

attributes (listMap): the list of attributes (both data and metadata)

value: a string representation of the attribute value

isComplex (boolean): true if the attribute is a feature (see Complex Features ), false otherwise

type (string or FeatureType): attribute type: if isComplex is false, the fully qualified Java class name; if isComplex is true, a FeatureType

rawValue: the actual attribute value (is isComplex is true rawValue is a Feature)

name (string): the type name (same as typeName)

title (string): The title configured in the admin console

abstract (string): The abstract for the type

description (string): The description for the type

keywords (list): The keywords for the type

metadataLinks (list): The metadata URLs for the type

SRS (string): The layer’s SRS

nativeCRS (string): The layer’s coordinate reference system as WKT

FeatureCollection (map)

features (list of Feature, see above)

type (FeatureType, see above)

request (map)

Contains the GetFeatureInfo request parameters and related values.

environment (map)

Allows accessing several environment variables, in particular those defined in:

JVM system properties OS environment variables web.xml context parameters

Allows accessing math functions.

${request.LAYERS} ${request.ENV.PROPERTY}

environment

${environment.GEOSERVER_DATA_DIR} ${environment.WEB_SITE_URL}
${Math.max(request.NUMBER1,request.NUMBER2)}

Table Of Contents

  • Template Lookup
  • Common Data Models

Continue Reading

  • Previous: Tutorials
  • Next: GeoRSS

Known GeoServer issues

  • Jira issue tracker
  • ALL TUTORIALS
  • SPRING BOOT

Java Freemarker Templates (FTL) Tutorial with HTML

ftl assign map

Freemarker Templates

Resolve freemarker jar dependency using gradle, project structure in eclipse.

Java Freemarker Templates  (FTL) Tutorial  with HTML Example

Create HTML Template using Freemarker Template Language

Create configuration instance, create a data model with java bean, instantiate the template, process data model to generate output in file and console, main class with complete code, html output, download source code.

ARVIND RAI

©2024 concretepage.com | Privacy Policy | Contact Us

  • FreeMarker 中文官方参考手册
  • Alpha. index
  • Expressions
  • #directives
  • name :变量的名字。 它不是表达式。而它可以写作是字符串,如果变量名包含保留字符这是很有用的, 比如 <#assign "foo-bar" = 1> 。 请注意这个字符串没有展开插值(如 "${foo}" ); 如果需要赋值一个动态创建的名字,那么不得不使用 这个技巧 。
  • = :赋值操作符。 它也可以是一个简写的赋值操作符(从 FreeMarker 2.3.23 版本开始): ++ , -- , += , -= , *= , /= 或 %= 。比如 <#assign x++> 和 <#assign x = x + 1> 是一样的,并且 <#assign x += 2> 和 <#assign x = x + 2> 是相同的。 请注意, ++ 通常意味着算术加法 (对于非数字将会失败),不像 + 或 += 可以进行字符连接等重载操作。
  • value : 存储的值。是表达式。
  • namespacehash :(通过 import ) 为命名空间创建的哈希表。是表达式。

使用该指令你可以创建一个新的变量, 或者替换一个已经存在的变量。注意仅仅顶级变量可以被创建/替换 (也就是说你不能创建/替换 some_hash.subvar , 除了 some_hash )。

关于变量的更多内容,请阅读: 模板开发指南/其它/在模板中定义变量

比如:变量 seq 存储一个序列:

比如:变量 x 中存储增长的数字:

作为一个方便的特性,你可以使用一个 assign 标记来进行多次定义。比如这个会做上面两个例子中相同的事情:

如果你知道什么是命名空间: assign 指令在命名空间中创建变量。通常它在当前的命名空间 (也就是和标签所在模板关联的命名空间)中创建变量。但如果你是用了 in namespacehash , 那么你可以用另外一个 命名空间 来创建/替换变量。 比如,这里你在命名空间中 /mylib.ftl 创建/替换了变量 bgColor :

assign 的极端使用是当它捕捉它的开始标记和结束标记中间生成的输出时。 也就是说,在标记之间打印的东西将不会在页面上显示, 但是会存储在变量中。比如:

请注意,你不应该使用它来往字符串中插入变量:

  • What is FreeMarker?
  • Version history

Handy stuff

  • Try template online
  • Expressions cheatsheet
  • .special_vars
  • Chinese Manual on Github
  • FreeMarker on Github
  • Follow us on Twitter
  • Report a bug
  • Ask a question
  • Mailing lists
  • Stack Overflow

Generated for: Freemarker 2.3.23 Last generated: 2015-09-18 14:38:51 GMT

© 1999 –2015 The FreeMarker Project . All rights reserved.

ViralPatel.net

How To Iterate HashMap in FreeMarker (FTL)

by Viral Patel · May 2, 2012

In this short article we will see how to iterate an HashMap in FreeMarker template. Consider below code which is normally used to iterate a List in FTL.

Here in above code, we created a List object and passed it to FTL page. In FTL we used <#list> to iterate and print its values.

Problem Statement

So here’s the problem statement. I have an Hashmap which I want to iterate and display in my FTL (FreeMarker) template. Consider following code in Java. So how to iterate this Hashmap in FTL and display its values?

Well, the above hashmap can be iterated in FTL using following code:

In above code, we used ?keys attribute to get the keySet of HashMap . This key set is iterated and corresponding value is fetched by user.get(key) method. Note: One thing that’s worth noting here is that the sequence in which the values are printing may be different then the actual sequence in which values are added in hashmap. This is because, hashmap doesn’t preserve order or values. If you want to preserve the sequence of keys use LinkedHashMap .

Hope this helps.

Tags: Freemarker FTL java code

  • Next story How To Pick Image From Gallery in Android App
  • Previous story Batch Insert In Java – JDBC

You may also like...

Loading Java Properties Files

Loading Java Properties Files

Creating ZIP and JAR Files in Java

Creating ZIP and JAR Files in Java

R.I.P Sun: James Gosling paying Respects

R.I.P Sun: James Gosling paying Respects

How to Add Password Protection to PDF using iText in Java

How to Add Password Protection to PDF using iText in Java

10 comments.

ftl assign map

Nice one, exactly what I was looking for! Thanks for the post!

ftl assign map

How do i access the next element in a sequence in freemarker

I have tried this but doesnt work

ftl assign map

How do I iterate over a hashmap<String,List> in freemarker? abc() takes as input only strings or arrays. Not lists & the hashmap which I am looking at contains Keys as String & Value as a list of strings. I want the output to be like :

A= apple,mango,banana B = x,e,t,

abc().setTargeting(‘${key?js_string}’,’${key_value_list_map[key]}’);

ftl assign map

Nice Article. But when I try this:

${key} = ${criteriaMap[key]}

It throws exception: freemarker.core.InvalidReferenceException: Expression criteriaMap[key] is undefined.

However, If i print key only using ${key} , the code works. I dont know why “criteriaMap[key]” is causing trouble.

Thanks in advance

PS: There is a Line in your article “corresponding value is fetched by user.get(key) method.” where is user in the article, its confusing.

ftl assign map

Staring from FreeMarker 2.3.25 you can do this: ${key} = ${value}

My last comment was mangled… so again, staring from FreeMarker 2.3.25 you can do this:

${key} = ${value}

I have no idea what the syntax of the comments is… a last attempt:

ftl assign map

Hi, I’m unable to get the desired output and getting following error: FreeMarker template error: The following has evaluated to null or missing: ==> key [in template “template/xyz.ftl” at line 35, column 19]

Code Snippet:

FROM HERE [#if sourceList?? && sourceList?has_content] Source: ${sourceList}

${key} = ${value};

[#else] sourceList is empty [/#if] TILL HERE

Output (after commenting out [#– ${key} = ${value}; –]) FROM HERE

Source: {a12=Test} List:

TILL HERE Would appreciate all the help.

ftl assign map

when I iterate , I am getting unnecessary key and values like,size, clone, equals etc.. how to avoid those values.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

FreeMarker

  • Report a Bug
  • Apache FreeMarker Manual
  • Template Language Reference
  • Built-in Reference

Built-ins for hashes

  • Alpha. index
  • Expressions
  • #directives

A sequence that contains all the lookup keys in the hash.

Note that not all hashes support this (ask the programmer if a certain hash allows this or not).

Since hashes do not define an order for their sub variables in general, the order in which key names are returned can be arbitrary. However, some hashes maintain a meaningful order (ask the programmer if a certain hash does that or not). For example, hashes created with the above { ... } syntax preserve the same order as you have specified the sub variables.

To list both the keys and the values, you can use <#list attrs as key, value>...<#list> ; see the list directive .

A sequence that contains all the variables (the values in the key-value pairs) in the hash.

As of the order in which the values are returned, the same applies as with the keys built-in; see there. Furthermore, it's not guaranteed that the order of the values corresponds to the order of the keys returned by the keys build-in.

  • 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. World map

    ftl assign map

  2. Ein Jahrzehnt FTL: Faster Than Light

    ftl assign map

  3. Steam Community :: Guide :: FTL: Ship and Layout Unlocking Guide

    ftl assign map

  4. Level map

    ftl assign map

  5. FTL Faster Than Light: How To Unlock Every Ship

    ftl assign map

  6. FTL: Ship and Layout Unlocking Guide

    ftl assign map

VIDEO

  1. Customer Mining Setup and Profit

  2. Law must align with reality

  3. FORTNITE ELIMINATIONS (CHAPTER 5 SEASON 2) #343

  4. top comment changes Europe day13 .#geography

  5. IF GUNS CAN TALK🤣 IN FREE FIRE || #shorts #shortsfeed #mobtra #viral #ytshort #funny #funnyshorts

  6. Easiest ENDERMAN XP farm in Minecraft Bedrock 1.20 ( tutorial )

COMMENTS

  1. assign

    Synopsis <#assign name1=value1 name2=value2... nameN=valueN> or <#assign same as above... in namespacehash> or <#assign name> capture this </#assign> or <#assign name in namespacehash> capture this </#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 <# ...

  2. How to create a list of map in FTL (Freemarker)

    I have a map of list testMap and the list inside the testMap has a list of maps. I want to separate the testMap into 2 maps testMap1 and testMap2 based on the value of the key in the lists. This is what I have tried. <#assign testMapList = testMap[key]>. <#assign testList1 = []>. <#assign testList2 = []>. <#list testMapList as testList>.

  3. Using FreeMarker templates (FTL)- Tutorial

    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.

  4. FreeMarker Common Operations

    The answer is a resounding 'yes'! >> Demystifying Microservices for Jakarta EE & Java EE Developers. 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.

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

    Generic form 1: <#list sequence as item >. Part repeated for each item. <#else>. Part executed when there are 0 items. </#list>. Where: The else part is optional, and is only supported since FreeMarker 2.3.23. sequence : Expressions evaluates to a sequence or collection of the items we want to iterate through.

  6. Freemarker Templates

    Freemarker is a simple yet powerful template engine that GeoServer uses to allow user customization of outputs. In particular, at the time of writing it's used to allow customization of GetFeatureInfo, GeoRSS and KML outputs. Freemarker allows for simple variable expansions, as in $ {myVarName}, expansion of nested properties, such as in ...

  7. FreeMarker Manual

    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

  8. Built-ins for sequences

    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 ...

  9. Java Freemarker Templates (FTL) Tutorial with HTML

    Here we set Freemarker version, location of FTL file, default encoding etc. Create a Data Model with Java Bean To create a data model, we are using a java Map with String and Object data type. We will create our java bean to hold the values. The Map key must match with Freemarker template variables.

  10. ftl

    An FTL namespace is made for a template when: (a) the template is the "main" template, that is, it is not invoked as a result of an <#include. ...>, but it is directly invoked ( with the process Java method of class Template or Environment ); (b) the template is invoked directly with <#import. ...>. output_format: Specifies the output format of ...

  11. assign

    概要 <#assign name1=value1 name2=value2... nameN=valueN> 或 <#assign same as above... in namespacehash> 或 <#assign name> capture this </#assign> 或 <#assign name in namespacehash> capture this </#assign>. 这里: name:变量的名字。它不是表达式。而它可以写作是字符串,如果变量名包含保留字符这是很有用的, 比如 <#assign "foo-bar" = 1>。

  12. How To Iterate HashMap in FreeMarker (FTL)

    Nice Article. But when I try this: ${key} = ${criteriaMap[key]} It throws exception: freemarker.core.InvalidReferenceException: Expression criteriaMap[key] is undefined.

  13. Expressions

    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 ...

  14. FreeMarker学习之assign指令

    地址:${info.address} 描述. 使用该指令你可以创建一个新的变量, 或者替换一个已经存在的变量。. 比如:变量 seq 存储一个序列:. <#assign seq = ["foo", "bar", "baz"]>. 比如:变量 x 中存储增长的数字:. <#assign x++>. 可以使用一个 assign 标记来定义定义多个变量. <#assign.

  15. Working with JSON in Freemarker

    As the name implies, Freemarker also evaluates any expressions in the String, which may or may not be what you want. For example, the reference ${name} is resolved, so the word "junk" appears in the output, even though it is not resolved through the assign tag (here I explicitly broke up the reference to show that ?eval is resolving it):

  16. Loop variable built-ins

    Loop variable built-ins only exists since FreeMarker 2.3.23. These built-ins you can only use with the loop variable of the list and items directives (and of the deprecated foreach directive). Some explanation of that follows ( loopVar ?index returns the 0-based index in the listable value we iterate through):

  17. Google Maps

    Find local businesses, view maps and get driving directions in Google Maps.

  18. Handling null values in Freemarker

    has_content, next to null-checking, also checks if the value is not empty.This works for strings, sequences, hashes or collections. If the object is a date, boolean or a number, then it acts as non-empty. For all other types it will act as empty.

  19. Built-ins for hashes

    values. A sequence that contains all the variables (the values in the key-value pairs) in the hash. ${v} mouse. 50. Note that not all hashes support this (ask the programmer if a certain hash allows this or not). As of the order in which the values are returned, the same applies as with the keys built-in; see there.