Timur Nugmanov
Timur Nugmanov

Reputation: 893

How to embed a .yaml.erb into another .yaml.erb while keeping indentation?

Suppose I have two files, parent.yaml.erb and and child.yaml.erb and I would like to include the contents of child.yaml.erb inside of parent.yaml.erb and calculate it in context of parent.yaml.erb. Example:

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 %>

I expect this result:

expected_result.yaml:

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

What I get instead is:

result.yaml:

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

  b:

    c: 4

Using trim_mode option from documentation doesn't help.

How do I achieve expected result with correct indentation?

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

Upvotes: 0

Views: 1481

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

You could do it this way.

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 -%>

Some explanation

  • I had to enable trim mode by passing nil and "-" as 2nd and 3rd arguments to ERB.new().
  • With trim mode enabled, I can trim unwanted white space using <$- and -%>.
  • I used gsub to indent by 4 spaces.

Of course, as noted in comments, it could be better to read the YAML data into memory as a hash, although I do realise you lose a lot of control of the output that way.

Upvotes: 1

Related Questions