引用
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.x</version>
</dependency>
Freemarker支持直接传入字符串作为模板,而不仅限于从文件中加载模板。下面是使用Freemarker直接传入字符串的示例:
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerExample {
public static void main(String[] args) throws IOException, TemplateException {
// 创建Freemarker配置
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
// 创建一个字符串作为模板
String templateString = "<html>\n" +
"<head>\n" +
"<title>Welcome ${name}!</title>\n" +
"</head>\n" +
"<body>\n" +
"<h1>Welcome ${name}!</h1>\n" +
"<p>Age: ${age}</p>\n" +
"</body>\n" +
"</html>";
// 将字符串转换为模板
Template template = new Template("myTemplate", templateString, configuration);
// 准备数据
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("name", "John");
dataModel.put("age", 25);
// 合并模板和数据
StringWriter writer = new StringWriter();
template.process(dataModel, writer);
String output = writer.toString();
// 输出结果
System.out.println(output);
}
}
在上述示例中,我们直接将HTML字符串作为模板,通过 new Template("myTemplate", templateString, configuration)
创建了模板对象。然后,我们按照之前的步骤准备数据、合并模板和数据,并输出结果。
通过这种方式,你可以在代码中直接定义模板字符串,而无需从外部文件加载模板。这在一些特定场景下非常有用,例如动态生成邮件内容、生成临时HTML页面等。
VUE版
npm install handlebars
# or
yarn add handlebars
const Handlebars = require("handlebars");
const template = Handlebars.compile("Name: {{name}}");
console.log(template({ name: "Nils" }));