首页 > 解决方案 > 使用 Thymeleaf 的动态模板解析器

问题描述

我们需要动态解析 html 或文本模板。具有可变占位符的模板内容(字符串)将在数据库中可用。

我们必须使用变量的实际值按需动态解析它们并获得最终的字符串内容。

示例:(不是完整的代码)

String myHtmlTemplateContent = "<h1>Hi ${first_name} ${last_name}</h1>";
Map<String, Object> myMapWithValues = ..;
engine.resolve(myHtmlTemplateContent , myMapWithValues );

如果我们有办法使用 thymeleaf 或是否可以使用 thymeleaf 模板引擎来解决问题,将会很有帮助。

标签: javaspringspring-bootthymeleaftemplate-engine

解决方案


您需要创建一个 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"
                        )) );

推荐阅读