如何在保持缩进的同时将.yaml.erb嵌入另一个.yaml.erb?

问题描述 投票:0回答:1

假设我有两个文件,parent.yaml.erbchild.yaml.erb,我想在里面包含child.yaml.erb的内容parent.yaml.erb并在parent.yaml.erb的上下文中进行计算。示例:

parent.yaml.erb

name: parent
first:
  second:
    third: something
    <%= ERB.new(File.read('child.yaml.erb')).result(binding) %>

child.yaml.erb

<% if some_condition %>
a:
  b:
    c: <%= 2+2 %>
<% end %>

我希望得到这个结果:

expected_result.yaml

name: parent
first:
  second:
    third: something
    a:
      b:
        c: 4

我得到的是:

result.yaml

name: parent
first:
  second:
    third: something
    *[whitespace ends here]*
a:

  b:

    c: 4

使用documentation中的trim_mode选项没有帮助。

如何通过正确的缩进获得预期的结果?

ruby 2.6.4p104 (2019-08-28 revision 67798) [x86_64-linux]

ruby yaml erb
1个回答
1
投票

您可以这样操作。

parent.yaml.erb

name: parent
first:
  second:
    third: something
<%- content = ERB.new(File.read("child.yaml.erb"), nil, "-").result().gsub(/^/,"    ") -%> 
<%= content -%> 

child.yaml.erb

<% if some_condition -%>
a:
  b:
    c: <%= 2+2 %>
<% end -%>

一些解释

  • 我必须通过将nil"-"作为第二和第三参数传递给ERB.new()来启用修整模式。
  • 启用修剪模式后,可以使用<$--%>修剪不需要的空白。
  • 我用gsub缩进了4个空格。

当然,正如评论中指出的那样,最好将YAML数据作为哈希读取到内存中,尽管我确实意识到您会以这种方式失去对输出的很多控制。

© www.soinside.com 2019 - 2024. All rights reserved.