假设我有两个文件,parent.yaml.erb和child.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]
您可以这样操作。
name: parent
first:
second:
third: something
<%- content = ERB.new(File.read("child.yaml.erb"), nil, "-").result().gsub(/^/," ") -%>
<%= content -%>
<% if some_condition -%>
a:
b:
c: <%= 2+2 %>
<% end -%>
nil
和"-"
作为第二和第三参数传递给ERB.new()
来启用修整模式。 <$-
和-%>
修剪不需要的空白。gsub
缩进了4个空格。当然,正如评论中指出的那样,最好将YAML数据作为哈希读取到内存中,尽管我确实意识到您会以这种方式失去对输出的很多控制。