java 给bartender模板传递数据
时间: 2023-07-16 14:13:09 浏览: 80
在 Java 中,可以使用模板引擎来生成动态内容。常见的模板引擎有 Freemarker、Velocity 等。这里以 Freemarker 为例,介绍如何给 Bartender 模板传递数据。
1. 添加依赖
首先需要在项目中添加 Freemarker 的依赖。如果使用 Maven,可以在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
```
2. 创建模板
创建一个 Bartender 模板文件,例如 `hello.ftl`,内容如下:
```html
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello ${name}!</h1>
</body>
</html>
```
`${name}` 是一个占位符,将在 Java 代码中被替换成真正的数据。
3. 渲染模板
在 Java 代码中,可以使用 Freemarker 的 API 来渲染模板。以下代码演示了如何将数据传递给模板,并将渲染结果输出到标准输出:
```java
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
public class BartenderDemo {
public static void main(String[] args) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setClassForTemplateLoading(BartenderDemo.class, "/");
Template template = cfg.getTemplate("hello.ftl");
Map<String, Object> data = new HashMap<>();
data.put("name", "World");
OutputStreamWriter writer = new OutputStreamWriter(System.out);
template.process(data, writer);
writer.flush();
}
}
```
其中 `setClassForTemplateLoading` 方法指定了模板文件的位置,这里设置为当前类所在的 package。`process` 方法将数据和输出流作为参数,将渲染结果输出到指定的输出流中。
运行程序,输出结果如下:
```html
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
```
可以看到,模板中的 `${name}` 被替换成了 `World`。