【问题标题】:Resolving template from resources/templates _and_ string从资源/模板_and_字符串中解析模板
【发布时间】:2020-02-24 19:25:02
【问题描述】:

在我的应用程序中,我需要使用“硬连线”html 模板,我将通过将它们添加到 resources/templates 和“动态”文本模板来烘焙它们,我想在运行时将它们存储在 Strings 中。

我的代码如下所示:

@Autowired
SpringTemplateEngine templateEngine;

templateEngine.addTemplateResolver(new DynamicTemplateResolver());

Context context = new Context();
context.setVariable("foo1", ... );

templateEngine.process("eitherStaticOrDynamic", context, output);

问题在于实现ITemplateResolverDynamicTemplateResolver。我尝试使用Process string templates with thymeleaf 3 提供的示例,但它们似乎不再适用于当前版本的 Spring。

如何从 Strings 解析模板?我使用 Spring Boot 2.2

【问题讨论】:

    标签: spring spring-boot templates thymeleaf


    【解决方案1】:

    我想我找到了解决方案。我的错误是基于误解。 Thymeleaf 为这个 javadoc 提供了一个StringTemplateResolver

    ...此模板解析器将考虑正在解析的模板 作为模板本身,这就是它的内容。没有外部文件或 因此将访问资源。 ...

    隐藏在这条评论中(至少对我来说)是这样一个事实,即给定的字符串被认为是一个 模板,而不是搜索模板 name。这意味着,如果您提供foo = [(${foo})],则不会将其视为需要按名称查找的模板,而是视为(在本例中为文本)模板!

    这并将我的代码更改为此解决了我的问题:

    StringTemplateResolver tr = new StringTemplateResolver();
    tr.setTemplateMode(TemplateMode.TEXT);
    

    如果没有此设置,我的模板将无法解析,因为文本模式模板遵循与 html 模板不同的语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 2013-08-28
      • 2015-11-11
      • 2021-04-09
      • 2020-12-01
      • 2022-10-17
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多