Reputation: 1728
I'm trying to use ERB with a plain text file. Here's the content of the plain text file:
<% if true %>
<%= 'bar' %>
<% end %>
<%= 'foo' %>
<%= 'bar' %>
The result I get with ERB is:
bar
foo
bar
The result I want to get is:
bar
foo
bar
without the empty newlines before "bar" and "foo".
Now, I know this is because ERB is configured (by default) to work with HTML files. What I want it to do is work with a plain text file in my case. I'm aware this is "somehow" possible because in Rails, when you work with Rails mailer to configure a plain text file, this doesn't happen.
Here's the big picture of what I'm trying to do: I'm trying to write a plain text article, but have some Ruby code in-between. I figured I'd use ERB for this, but the first stumbling block I got was this.
Upvotes: 6
Views: 4310
Reputation: 58324
In it's default mode, ERB treats the text very literally outside of the <% ... %>
expressions. So think of your text as being a stream that looks like this:
<% if true %><LF><%= 'bar' %><LF><% end %><LF><%= 'foo' %><LF><%= 'bar' %><LF>
As you can see, you'll get a line feed before "bar" and two line feeds before "foo". I.e., the output will be:
<blank line>
bar
<blank line>
foo
bar
The way around it is to use the "trim mode" option for erb
. Write your file as:
<% if true -%>
<%= 'bar' %>
<% end -%>
<%= 'foo' %>
<%= 'bar' %>
Then call erb -T - your_erb_file.erb
bar
foo
bar
The -T -
tells erb
to remove the end of line if the line ends with -%>
. Leading whitespaces are removed if the erb
directive starts with <%-
. See, for example, this manual page for erb
for details.
Upvotes: 7