原文:https://www.jianshu.com/p/e2be73f07b3f
1、在pom.xml
中添加依赖
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl-framework-starter</artifactId>
<version>1.1.55.RELEASE</version>
</dependency>
2、添加控制器Test1Controller
,代码如下
package com.example.demo.controller;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Test1Controller {
@RequestMapping("/hello")
public String welcome(){
return "hello,world";
}
@RequestMapping("/hello2")
public String BeetlString() throws Exception {
//new一个模板资源加载器
StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
/* 使用Beetl默认的配置。
* Beetl可以使用配置文件的方式去配置,但由于此处是直接上手的例子,
* 我们不去管配置的问题,只需要基本的默认配置就可以了。
*/
Configuration config = Configuration.defaultConfiguration();
//Beetl的核心GroupTemplate
GroupTemplate groupTemplate = new GroupTemplate(resourceLoader, config);
//我们自定义的模板,其中${title}就Beetl默认的占位符
String testTemplate="<html>
" +
"<head>
" +
" <title>${title}</title>
" +
"</head>
" +
"<body>
" +
" <h1>${name}</h1>
" +
"</body>
" +
"</html>";
Template template = groupTemplate.getTemplate(testTemplate);
template.binding("title","This is a test template Email.");
template.binding("name", "beetl");
//渲染字符串
String str = template.render();
System.out.println(str);
return str;
}
}