如何使用Thymeleaf处理YAML文件?

时间:2017-02-24 10:36:04

标签: 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: TCP
    name: https
  selector:
    app: nginx

app.name来自我在运行时解析的另一个YAML文件。

到目前为止我尝试过:

  1. 使用MessageSource

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

    map.put("app.name", "test");
    context.setVariables(map); // contains app.name
    
  3. 但我一直收到错误:

    Exception evaluating OGNL expression: "app['name']
    ...
    Caused by: ognl.OgnlException: source is null for getProperty(null, "name")
    

    使用Thymeleaf 3.0.3.RELEASE。我正在使用Spring而不使用Spring,因为spring-boot-starter-thymeleaf带来了HTML所需的大量包袱,我决定自己实例化模板解析器和引擎。似乎人们很少使用Thymeleaf处理TEXT;我遇到的所有例子都是HTML。

    我也想知道如何在我的模板中包含YAML片段。

    修改: 感谢@Metroids,我得到了它的工作。以下是我的示例应用的link,以防其他人遇到类似问题。

1 个答案:

答案 0 :(得分:2)

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

Map<String, Object> app = new HashMap<>();
app.put("name", "test");

Context context = new Context();
context.setVariable("app", app);
engine.process("template", context);

使用map.put("app.name", "test");不是一个好主意,因为something.something的语法在表达式语言中有意义(在对象上调用getter / setter)。

编辑:包含文本模板将如下所示:

<强> A.TXT

blah blah blah 
[# th:insert="b"/] 
blah blah blah 

<强> b.txt

Text in b.txt
that should be included

编辑2:如果你想使用消息,而不是一个上下文应该可以工作:

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