gpt4 book ai didi

java - 使用 Thymeleaf 的动态模板解析器

转载 作者:行者123 更新时间:2023-12-04 08:45:43 28 4
gpt4 key购买 nike

我们有动态解析 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 一起使用:

@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>

如果你想手动处理模板,你可以 Autowiring 模板引擎并手动使用它:

@Autowired SpringTemplateEngine templateEngine;

String emailContent = templateEngine.process( "mytemplate",
new Context( Locale.ENGLISH, Map.of(
"first_name", "Abel",
"last_name", "Lincon"
)) );

关于java - 使用 Thymeleaf 的动态模板解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64339712/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com