Spring 如何使用Thymeleaf处理YAML文件?

Spring 如何使用Thymeleaf处理YAML文件?,spring,thymeleaf,template-engine,Spring,Thymeleaf,Template Engine,我正在尝试使用Thymeleaf处理YAML文件。下面给出了一个示例文件: apiVersion: v1 kind: Service metadata: name: [[${app['name']}]] labels: app: [[${app['name']}]] spec: type: NodePort ports: - port: 80 protocol: TCP name: http - port: 443 protocol: TC

我正在尝试使用Thymeleaf处理YAML文件。下面给出了一个示例文件:

apiVersion: v1
kind: Service
metadata:
  name: [[${app['name']}]]
  labels:
    app: [[${app['name']}]]
spec:
  type: NodePort
  ports:
  - port: 80
    protocol: TCP
    name: http
  - port: 443
    protocol: TCP
    name: https
  selector:
    app: nginx
app.name
来自我在运行时解析的另一个YAML文件

到目前为止,我所尝试的:

  • 使用
    属性创建
    消息源

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    StandardMessageResolver messageResolver = new StandardMessageResolver();
    messageResolver.setDefaultMessages(props); // contains app.name
    templateEngine.setMessageResolver(messageResolver);
    
  • 在上下文中设置变量

    map.put("app.name", "test");
    context.setVariables(map); // contains app.name
    
  • 但我一直在犯错误:

    Exception evaluating OGNL expression: "app['name']
    ...
    Caused by: ognl.OgnlException: source is null for getProperty(null, "name")
    
    使用Thymeleaf 3.0.3.0版本。我使用的是Spring,而不是Spring,因为
    Spring启动程序thymeleaf
    带来了很多HTML所需的负担,所以我决定自己实例化模板解析器和引擎。人们似乎很少使用Thymeleaf处理文本;我遇到的所有示例都是HTML

    我还想知道如何在模板中包含YAML片段

    编辑
    多亏了@Metroids,我才得以工作。以下是我的示例应用程序的示例,以防其他人有类似的问题。

    我认为关于如何访问此处的属性存在一些困惑。。。如果要在模板中使用表达式
    ${app['name']}
    ,则上下文应如下所示:

    Map<String, Object> app = new HashMap<>();
    app.put("name", "test");
    
    Context context = new Context();
    context.setVariable("app", app);
    engine.process("template", context);
    
    b.txt

    blah blah blah 
    [# th:insert="b"/] 
    blah blah blah 
    
    Text in b.txt
    that should be included
    
    编辑2:如果您想使用消息,而不是上下文,则应该可以:

    apiVersion: v1
    kind: Service
    metadata:
      name: [[#{app.name}]]
      labels:
        app: [[#{app.name}]]
    

    这就是我最终所做的。我的印象是,
    MessageResolver
    能够解析
    app.name
    ,因为这是消息键的常见格式,但它没有。请用包含的片段更新你的回复,我会接受的。啊,你在thymeleaf论坛上是同一个人。。。明白了,哈哈。我发现
    [#th:text=“#{app.name}”/
    也适用于邮件。不过,您的语法更简洁。谢谢你的帮助。为了让大家受益,我编辑了我的问题,添加了一个指向我正在开发的示例应用程序的链接。