java - 使用 Thymeleaf 的动态模板解析器
问题描述
我们需要动态解析 html 或文本模板。具有可变占位符的模板内容(字符串)将在数据库中可用。
我们必须使用变量的实际值按需动态解析它们并获得最终的字符串内容。
示例:(不是完整的代码)
String myHtmlTemplateContent = "<h1>Hi ${first_name} ${last_name}</h1>";
Map<String, Object> myMapWithValues = ..;
engine.resolve(myHtmlTemplateContent , myMapWithValues );
如果我们有办法使用 thymeleaf 或是否可以使用 thymeleaf 模板引擎来解决问题,将会很有帮助。
解决方案
您需要创建一个 thymeleaf 模板mytemplate.html
,其中包含:
<h1 th:text="Hi ${first_name} ${last_name}"></h1>
并将其与在模型中设置变量的 mvc 控制器一起使用:
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("first_name", "Abel");
model.addAttribute("last_name", "Lincon");
return "mytemplate"; //resolves to mytemplate.html
}
}
它会渲染<h1>Hi Abel Lincon</h1>
如果要手动处理模板,可以自动装配模板引擎并手动使用它:
@Autowired SpringTemplateEngine templateEngine;
String emailContent = templateEngine.process( "mytemplate",
new Context( Locale.ENGLISH, Map.of(
"first_name", "Abel",
"last_name", "Lincon"
)) );
推荐阅读
- html - Angular 在 datepicker 日历中添加切换开关
- c - 我可以只运行一个端口在 Pktgen 中连续发送数据包吗?
- python - try-except 和 RuntimeWarning
- json - 在 json 中是否有一种格式可用于与 REST 服务器通信?
- r - 如何将具有类间隔的数据从excel导入到R
- jupyter-notebook - cocalc:如何添加 julia 内核?
- arrays - 通过firebase firestore上的数组内的对象值查询
- html - 填写一个框固定宽度
- css - 如何从图像元素中分离背景不透明度转换
- mysql - 我有三个查询链接以将一个表从 oracle 提取到 SAS,但第三个查询没有输出任何输出,我没有发现错误