Freemarker

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>&copy; 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的模板继承和列表处理能力,适用于构建复杂且可重用的页面结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值