【问题标题】:Pebble templating for YAML file用于 YAML 文件的 Pebble 模板
【发布时间】:2021-07-09 16:43:19
【问题描述】:

我正在为 YAML 格式的配置文件尝试 Pebble 模板。此值来自另一个 YAML 文件。那就是——

  1. value.yml 包含:-
    server:
     -
      box1:
        host:"12345"
  1. config.yml 包含:-
    server:
      -
       env: "abc"
       host: {{ server.box1.host }} 

我可以将 config.yml 读取为字符串并创建一个 Pebble 模板。使用评估,我可以用名称未嵌套的上下文变量替换模板(例如 {{ serverBox1Host }} --> 这有效)。

如果我使用 {{ server.box1.host }},我会得到 com.mitchellbosecke.pebble.error.RootAttributeNotFoundException: Root attribute [server] does not exist or can't be access and strict变量设置为真。 如果我将 strictVariables 设置为 false,则 {{ server.box1.host }} 将替换为空。

如何解决?

context.put("server.box1.host", "suriya" );

我参考了: https://www.programcreek.com/java-api-examples/?api=com.mitchellbosecke.pebble.PebbleEngine

我正在使用“字符串模板”:

new PebbleEngine.Builder()
                .strictVariables(true)
                .newLineTrimming(false)
                .loader(new StringLoader())
                .build();

谢谢

【问题讨论】:

    标签: java pebble


    【解决方案1】:

    您可以使用点 (.) 符号来访问作为对象的变量的属性。如果属性包含任何非典型字符,您可以使用下标符号 ([]) 代替。

    {{ foo.bar }}
    {{ foo["bar"] }}
    

    在幕后 foo.bar 将尝试以下技术来访问 foo 变量的 bar 属性:

    如果 foo 是一个地图,

    foo.get("bar")
    foo.getBar()
    foo.isBar()
    foo.hasBar()
    foo.bar()
    foo.bar
    

    另外,如果 foo 是一个 List,那么 foo[0] 可以用来代替 foo.get(0)。

    您可以在此处查看 pebble 文档:https://pebbletemplates.io/wiki/guide/basic-usage/

    【讨论】:

      【解决方案2】:

      解决了这个问题:

      在上下文中分配的变量名称类似于服务器 - context.put("server", new HashMap map1);

      并且 map1 有嵌套的 map,其键是 box1 和 host。宿主的价值是suriya。

      map1 :
      key - box1
      value - Map with key host and value suriya.
      

      在 Pebble 模板中能够访问 {{ server.box1.host }} 并以值“suriya”呈现

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-05
        • 2021-01-11
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 2021-11-23
        • 1970-01-01
        相关资源
        最近更新 更多