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

标签 java spring spring-boot thymeleaf template-engine

我们有动态解析 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/

相关文章:

spring-boot - Kafka 如何将生产者重试设置为无限

java - OSGi do两个包之间的特权调用

java - 如何在 JavaFX 形状中插入 HTML 文本?

java - 在 spring-web.xml 中配置多个数据源

java - Spring AOP setAdvice 仅在一种特定方法上

java - 在 Spring 中使用 Authentication 类测试 Controller

java - 为什么 Raspberry Pi 上的 JavaFX (3D) 不起作用,尽管它应该起作用?

java - 将 Windows 命名管道用于 IPC 的一种有效方法

java - 将全局变量 Hook 到 JSP (Spring) 中最优雅的方法是什么

java - Spring Boot 应用程序无法使用 Spring Boot Dashboard 在 Eclipse 中启动