Freemarker简介
Freemarker是一个用Java语言编写的模板引擎,用于基于模板和数据生成文本输出。它可以用于生成HTML网页、XML文档、电子邮件、配置文件等任何格式的文本。Freemarker将业务逻辑与表示逻辑分离,使得开发人员可以专注于功能实现,而设计师可以专注于页面布局。
快速入门
1. 添加依赖
如果你使用的是Maven项目,可以在pom.xml
中添加如下依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2. 配置环境
创建一个Configuration
对象,指定模板加载路径。
import freemarker.template.Configuration;
import freemarker.template.Template;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("path/to/your/templates/directory"));
3. 创建模型
模型是传递给模板的数据。
Map<String, Object> model = new HashMap<>();
model.put("name", "John Doe");
model.put("age", 30);
4. 加载并合并模板
Template temp = cfg.getTemplate("templateName.ftl");
Writer out = new PrintWriter(new FileOutputStream("output.html"), true);
temp.process(model, out);
案例一
假设你有一个简单的HTML模板helloWorld.ftl
:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Welcome, ${name}!</h1>
<p>You are ${age} years old.</p>
</body>
</html>
你可以使用以下Java代码生成HTML文件:
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import freemarker.template.*;
public class HelloWorld {
public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("templates"));
Map<String, Object> model = new HashMap<>();
model.put("name", "John Doe");
model.put("age", 30);
Template temp = cfg.getTemplate("helloWorld.ftl");
Writer out = new PrintWriter(new FileOutputStream("output.html"), true);
temp.process(model, out);
}
}
案例二
更复杂的案例可能涉及模板继承、列表循环、条件判断等。例如,你可能有如下的模板结构:
base.ftl
: 基础模板,包含头部和尾部。index.ftl
: 继承base.ftl
,添加动态内容。
base.ftl
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
</head>
<body>
<header>
<h1>Welcome to our site</h1>
</header>
<div id="content">
<#include "content.ftl">
</div>
<footer>
<p>© 2024 Our Company</p>
</footer>
</body>
</html>
index.ftl
<@base title="Home Page">
<#list items as item>
<div>
<h2>${item.title}</h2>
<p>${item.description}</p>
</div>
</#list>
</@base>
在这个例子中,base.ftl
是一个基础模板,index.ftl
通过@base
指令继承了基础模板,并传入了标题参数。index.ftl
还包含了对items
列表的循环。
这个案例展示了Freemarker的模板继承和列表处理能力,适用于构建复杂且可重用的页面结构。