Istvan
Istvan

Reputation: 8602

How to render an Array to a YAML list with ERB?

I am trying to render an Array with ERB to a YAML file.

Input:

arr = [1,2,3]

Expected output:

  ---
  tags:
    - 1
    - 2
    - 3

Code:

tags:
  <%- @arr.each do |tag| -%>
  - <%= tag %>
  <% end -%>
  - extra-tag

This renders the following YAML

---
tags:
  - 1 - 2 -3

Is there a way to render this properly?

Upvotes: 0

Views: 2122

Answers (1)

Kimmo Lehto
Kimmo Lehto

Reputation: 6041

The only problem I see in your example is the missing leading - from the closing <% end -%> (should be <%- end -%>).

# foo.erb:
<%- @arr = [1,2,3] -%>
tags:
  <%- @arr.each do |tag| -%>
  - <%= tag %>
  <%- end -%>
  - extra tag

Output:

$ erb -T - foo.erb
tags:
 - 1
 - 2
 - 3
 - extra tag

Without the leading - the result I get is different from yours:

tags:
  - 1
    - 2
    - 3
    - extra tag

Upvotes: 3

Related Questions