Using FreeMarker templates (FTL)- Tutorial
Lars Vogel, (c) 2012, 2016 vogella GmbHVersion 1.4,06.10.2016
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.
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. 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>
(theMap
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 ofmyObject.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 aString
, 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 fromString
objects.2. Installation of FreeMarker
To use FreeMarker download the latest version of it from the following webpage and add it to the classpath of your Java project.
http://freemarker.org/freemarkerdownload.html
3. Eclipse Integration
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…
http://download.jboss.org/jbosstools/updates/stable/kepler/
4. Basic example
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 namehelloworld.ftl
.<html>
<head>
<title>${title}
</head>
<body>
<h1>${title}</h1> <p>${exampleObject.name} by ${exampleObject.developer}</p> <ul>
<#list systems as system>
<li>${system_index + }. ${system.name} from ${system.developer}</li>
</#list>
</ul> </body>
</html>Create the following class which demonstrates the usage of Java objects in templates.
package com.vogella.freemarker.first; public class ValueExampleObject { private String name;
private String developer; public ValueExampleObject(String name, String developer) {
this.name = name;
this.developer = developer;
} public String getName() {
return name;
} public String getDeveloper() {
return developer;
} }Create the following class which creates the input for this template and creates the output.
package com.vogella.freemarker.first; import java.io.File;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.Version; public class MainTest { public static void main(String[] args) throws Exception { // 1. Configure FreeMarker
//
// You should do this ONLY ONCE, when your application starts,
// then reuse the same Configuration object elsewhere. Configuration cfg = new Configuration(); // Where do we load the templates from:
cfg.setClassForTemplateLoading(MainTest.class, "templates"); // Some other recommended settings:
cfg.setIncompatibleImprovements(new Version(, , ));
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // 2. Proccess template(s)
//
// You will do this for several times in typical applications. // 2.1. Prepare the template input: Map<String, Object> input = new HashMap<String, Object>(); input.put("title", "Vogella example"); input.put("exampleObject", new ValueExampleObject("Java object", "me")); List<ValueExampleObject> systems = new ArrayList<ValueExampleObject>();
systems.add(new ValueExampleObject("Android", "Google"));
systems.add(new ValueExampleObject("iOS States", "Apple"));
systems.add(new ValueExampleObject("Ubuntu", "Canonical"));
systems.add(new ValueExampleObject("Windows7", "Microsoft"));
input.put("systems", systems); // 2.2. Get the template Template template = cfg.getTemplate("helloworld.ftl"); // 2.3. Generate the output // Write output to the console
Writer consoleWriter = new OutputStreamWriter(System.out);
template.process(input, consoleWriter); // For the sake of example, also write output into a file:
Writer fileWriter = new FileWriter(new File("output.html"));
try {
template.process(input, fileWriter);
} finally {
fileWriter.close();
} }
}5. Useful FTL tricks
5.1. Reuse common template fragments
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 thetemplates
directory, and there create a file calledutils.ftl
, with this content:<#macro page>
<html>
<head>
<title>${title}
</head>
<body>
<h1>${title}</h1> <#-- This processes the enclosed content: -->
<#nested>
</body>
</html>
</#macro> <#macro otherExample p1 p2>
<p>The parameters were: ${p1}, ${p2}</p>
</#macro>Now you can simplify
helloworld.ftl
like this:<#import "lib/utils.ftl" as u> <@u.page>
<p>${exampleObject.name} by ${exampleObject.developer}</p> <ul>
<#list systems as system>
<li>${system_index + }. ${system.name} from ${system.developer}</li>
</#list>
</ul> <#-- Just another example of using a macro: -->
<@u.otherExample p1= p2= />
</@u.page>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.5.2. Variables
You can define and assign content to variables inside the FTL files for easy reuse.
<#assign var_link = "http://www.vogella.com/people/larsvogel.html"> <a href="${var_link}">About Lars Vogel</a>5.3. Handling null/undefined values
FreeMarker requires you to provide an explicit default for variables, so avoid values that are
null
or undefined:<!-- Acts like if the color was N/A if there's no color: -->
<p>Color: ${color!'N/A'}</p> <!-- Avoid the whole color row if there's no color: -->
<#if color??>
<p>Color: ${color}</p>
</#if>5.4. Escape
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:<#escape x as x?html>
<p>Sender: ${from}
<p>Title: ${title}
<p>Message: ${body}
</#escape>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.转载自:http://www.vogella.com/tutorials/FreeMarker/article.html
Using FreeMarker templates (FTL)- Tutorial的更多相关文章
- [Freemarker] - 使用struts的component调用freemarker的ftl模板方法
struts中的component标签,可以用来调用freemarker的ftl模板文件,使用component标签传参可以这样写: 使用property方式写法: <s:component t ...
- freemarker(FTL)常见语法大全
[转载]freemarker(FTL)常见语法大全 FreeMarker的插值有如下两种类型:1,通用插值${expr};2,数字格式化插值:#{expr}或#{expr;format} ${boo ...
- FreeMarker之FTL指令
assign指令 此指令用于在页面上定义一个变量 (1)定义简单类型: <#assign linkman="周先生"> 联系人:${linkman} (2)定义对象类型 ...
- freemarker【FTL】常见语法大全
FreeMarker的插值有如下两种类型:1,通用插值${expr};2,数字格式化插值:#{expr}或#{expr;format} ${book.name?if_exists } //用于判断如果 ...
- JAVAWEB使用FreeMarker利用ftl把含有图片的word模板生成word文档,然后打包成压缩包进行下载
这是写的另一个导出word方法:https://www.cnblogs.com/pxblog/p/13072711.html 引入jar包,freemarker.jar.apache-ant-zip- ...
- 修改freemarker的ftl时,不重启tomcat的办法(使用了springMVC)
一.在使用Freemarker 时,需要在spring-mvc.xml 配置文件中作如下配置: <!-- 配置freeMarker的模板路径 --> <bean id="f ...
- FTL(FreeMarker)基础
FreeMarker标签使用一.FreeMarker模板文件主要有4个部分组成1.文本,直接输出的部分2.注释,即<#--...-->格式不会输出3.插值(Interpolation):即 ...
- Freemarker 程序开发
Freemarker 程序开发 现在web开发中,多使用freemarker 来描述页面.通常会使用的macro来定义各种组件,从而达到UI组件的复用.结合使用其它的指定,可快速的描述一个html页面 ...
- Spring MVC 学习总结(七)——FreeMarker模板引擎与动态页面静态化
模板引擎可以让程序实现界面与数据分离,业务代码与逻辑代码的分离,这就提升了开发效率,良好的设计也使得代码复用变得更加容易.一般的模板引擎都包含一个模板解析器和一套标记语言,好的模板引擎有简洁的语法规则 ...
随机推荐
- 在CentOS系统中使用yum安装指定版本软件的方法
yum默认都是安装最新版的软件,这样可能会出一些问题,或者我们希望yum安装指定(特定)版本(旧版本)软件包.所以,就顺带分享yum安装指定(特定)版本(旧版本)软件包的方法. 过程如下: 假设这里是 ...
- 反编译android的apk
将要反编译的APK后缀名改为.rar或 .zip,并解压 得到其中的classes.dex文件(它就是java文件编译再通过dx工具打包而成的),将获取到的classes.dex放到之前解压出来的 ...
- com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command ' finished with non-zero exit value 1
Error:Execution failed for task ':lenovoAlbum:processReleaseResources'. > com.android.ide.common. ...
- 简单粗暴地理解 JavaScript 原型链 (一个充满歪门邪理的理解方法,有助于新手哦!)
原型链理解起来有点绕了,网上资料也是很多,每次晚上睡不着的时候总喜欢在网上找点原型链和闭包的文章看,效果极好. 不要纠结于那一堆术语了,那除了让你脑筋拧成麻花,真的不能帮你什么.简单粗暴点看原型链吧, ...
- swift基础:第三部分:对第一部分的补充说明
今天是我学习swift的第二天,虽然我和swift的距离有点远,但我相信,我会慢慢的接近这门语言的.好了,我们聊聊昨天晚上的事吧,昨天晚上下班早,回到家时,真是惊喜哈,宿舍那两做好了饭,等我吃饭,想对 ...
- 论文阅读(Xiang Bai——【PAMI2017】An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition)
白翔的CRNN论文阅读 1. 论文题目 Xiang Bai--[PAMI2017]An End-to-End Trainable Neural Network for Image-based Seq ...
- [liusy.api-SMJ]-创建工程范例 MAVEN archetype 学习阶段(一)
由于这个架构需要好多不同能力的工程,为了创建方便减少冗余,创建工程范例尤为重要 学习阶段: 参考资料 http://maven.apache.org/archetype/maven-archetype ...
- 图像开发的p2s模式:halcon+opencv的联动
[<zw版·Halcon与delphi系列原创教程> 图像开发的p2s模式:halcon+opencv的联动 尽管halcon功能强大,基本上cv只是halcon的一个子集,不过cv毕竟是 ...
- WebService "因 URL 意外地以 结束,请求格式无法识别" 的解决方法
最近在做一个图片上传的功能,js调用用webservice进行异步访问服务器,对于不是经常用webservice的菜鸟来说,经常会遇到以下的问题(起码我是遇到了) 在页面上写了js调用代码如下所示: ...
- 五步教你实现使用Nginx+uWSGI+Django方法部署Django程序
Django的部署可以有很多方式,采用nginx+uwsgi的方式是其中比较常见的一种方式. 在这种方式中,我们的通常做法是,将nginx作为服务器最前端,它将接收WEB的所有请求,统一管理请求.ng ...