东莞哪家做网站很有名的公司,电商网站建设信息,网络推广的目标,vps看网站蜘蛛Freemarker简介
Freemarker是一个用Java语言编写的模板引擎#xff0c;用于基于模板和数据生成文本输出。它可以用于生成HTML网页、XML文档、电子邮件、配置文件等任何格式的文本。Freemarker将业务逻辑与表示逻辑分离#xff0c;使得开发人员可以专注于功能实现#xff0c…Freemarker简介
Freemarker是一个用Java语言编写的模板引擎用于基于模板和数据生成文本输出。它可以用于生成HTML网页、XML文档、电子邮件、配置文件等任何格式的文本。Freemarker将业务逻辑与表示逻辑分离使得开发人员可以专注于功能实现而设计师可以专注于页面布局。
快速入门
1. 添加依赖
如果你使用的是Maven项目可以在pom.xml中添加如下依赖
dependencygroupIdorg.freemarker/groupIdartifactIdfreemarker/artifactIdversion2.3.31/version
/dependency2. 配置环境
创建一个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. 创建模型
模型是传递给模板的数据。
MapString, 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
headtitleHello World/title
/head
bodyh1Welcome, ${name}!/h1pYou 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));MapString, 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
headtitle${title}/title
/head
bodyheaderh1Welcome to our site/h1/headerdiv idcontent#include content.ftl/divfooterpcopy; 2024 Our Company/p/footer
/body
/htmlindex.ftl
base titleHome Page#list items as itemdivh2${item.title}/h2p${item.description}/p/div/#list
/base在这个例子中base.ftl是一个基础模板index.ftl通过base指令继承了基础模板并传入了标题参数。index.ftl还包含了对items列表的循环。
这个案例展示了Freemarker的模板继承和列表处理能力适用于构建复杂且可重用的页面结构。