ruby-on-railsrubyyamlerb

How to embed sub-templates in .yml.erb with <%= ERB.new(sub_template).result(binding) %>


I have the below parent.yml.erb:

template:
  spec:
    - image:
      env:
        - name: env_a
          valueFrom:
            ...
        - name: env_b
          valueFrom:
            ...
        - name: env_c
          valueFrom:
            ...
        - name: env_d
          valueFrom:
            ...

I want to extract out env_b and env_c into a separate child.yml.erb file and embed it in parent.yml.erb and I've tried the below.

parent.yml.erb:

template:
  spec:
    - image:
      env:
        - name: env_a
          valueFrom:
            ...
<%= ERB.new(File.read('child.yml.erb').gsub(/^/, ' ' * 8)).result(binding) %>
        - name: env_d
          valueFrom:
            ...

child.yml.erb:

- name: env_b
  valueFrom:
    ...
- name: env_c
  valueFrom:
    ...

The result after rendering parent.yml.erb with ERB.new(File.read('parent.yml.erb')).result(binding):

        - name: env_b
          valueFrom:
            ...
        - name: env_c
          valueFrom:
            ...
        - name: env_d
          valueFrom:
            ...

env_b, env_c, and everything below gets rendered but everything above <%= ERB.new(File.read('child.yml.erb').gsub(/^/, ' ' * 8)).result(binding) %> got removed. Is there something I'm doing wrong here?

The .gsub(/^/, ' ' * 8) is to keep the same indentation. I still have the same problem even if I remove the gsub.


Solution

  • When multiple ERB templates are being built at the same time using the same binding, then the eoutvar parameter needs to be passed. Otherwise they start overwriting each other's output. It can be any (unique) string.

    See docs

    parent.yml.erb:

    template:
      spec:
        - image:
          env:
            - name: env_a
              valueFrom:
                ...
    <%= ERB.new(File.read('child.yml.erb').gsub(/^/, ' ' * 8), eoutvar: 'child').result(binding) %>
            - name: env_d
              valueFrom:
                ...