Navarro
Navarro

Reputation: 1384

Indentation in ERB templates

I have the following entry in an erb template:

# Lorem Ipsum...
<% unless @foo['bar'] == nil %>
    <% @foo['bar'].each do |property, value| %>
        <%= "zaz.#{property} #{value}" %>
    <% end %>
<% end %>

That is parsed to:

# Lorem Ipsum...
       zaz.property value

How can I remove the leading spaces so that lines are not indented in the resolved template?

I would like to avoid using something like:

# Lorem Ipsum...
<% unless @foo['bar'] == nil %>
    <% @foo['bar'].each do |property, value| %>
<%= "zaz.#{property} #{value}" %>
    <% end %>
<% end %>

Upvotes: 14

Views: 4212

Answers (3)

Jacquen
Jacquen

Reputation: 1116

If you're controlling the string passed to ERB.new, then you can make yourself a new tag to use.

Given a template in a file:

<%~ 'hello' %>
    <%~ 'world' %>
<%~ '!' %>

Do:

string = File.read(file_path).gsub('<%~', '<%-%><%=')
print ERB.new(string, trim_mode: '-').result

And get:

hello
world 
!

I'd love it if ERB would include this tag itself, but until then I'm doing it myself.

Upvotes: -1

Stanislav Mekhonoshin
Stanislav Mekhonoshin

Reputation: 4386

The only solution I can offer is hackish adding <%- 'whatever here' %> before the <%= %> entry:

<% [1,2,3].each do |f| %>
    <%- 1 %><%= f %>
<% end %>

it outputs in irb

irb(main):018:0> ERB.new(File.read('f.txt'), nil, '-').result
=> "\n1\n\n2\n\n3\n\n"

Rails doc claims, that default value for ERB trim_mode is - http://edgeguides.rubyonrails.org/configuring.html#configuring-action-view

And according to https://www.systutorials.com/docs/linux/man/1-erb/ ERB should remove spaces before <%- when - mode is enabled.

Upvotes: 2

koffeinfrei
koffeinfrei

Reputation: 2045

You could indent the code instead of the ERB tags:

# Lorem Ipsum...
<% unless @foo['bar'] == nil %>
<%   @foo['bar'].each do |property, value| %>
<%=    "zaz.#{property} #{value}" %>
<%   end %>
<% end %>

Upvotes: 4

Related Questions