I need to be able to format unprinted logic lines in ERB without affecting the eventual text output of the template. At this point, I don't think that ERB supports such escaping.
This is my first major Ruby project. I am writing a code generator. My templates will include a considerable number of conditionals and enumerations. To make the template readable and maintainable, I need to be able to format the logical code and comments without distorting the eventual output.
E.g. Suppose I want this output:
Starting erbOutput
1
2
3
4
Ending erbOutput
I naively wrote the template something like so:
require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s %>
<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h).result
puts s
... but this produces
Starting erbOutput
0
1
2
3
4
Ending erbOutput
A straight print:
"Starting erbOutput\n\n\n0\n\n1\n\n2\n\n3\n\n4\n\n\nEnding erbOutput\n"
...makes it clear that the line-returns of the logic and comment lines are being included in the ERB output.
I can produce the desired output by cramming the template into this awkward form:
h=<<H
Starting erbOutput<%# comment %>
<%5.times do |e|%><%=e.to_s %>
<%end %><%# comment %>Ending erbOutput
H
... but I don't think I can debug and maintain templates without more readable formatting. Some of my conditionals and enumerations are as much as three levels deep and I comment heavily. Cramming all that on one or two lines makes the template utterly unreadable.
Is there a way to escape or otherwise suppress the line returns of logic an comment lines in ERB? Does one of the other commonly available Ruby template modules handle this better?
In case it matters, I am working in MacRuby 0.10 (implements Ruby 1.9.2) on MacOS 10.6.7.
Minus sign?
<%# comment -%>
<% 5.times do |e| -%>
<%= e.to_s -%>
<% end -%>
<%# comment -%>
As Rom1 and Kyle suggest, you can pass parameters to ERB.new
, but then, you will not get line breaks where you want.
require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s %>
<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h, nil, '<>').result
puts s
gives you
Starting erbOutput
01234Ending erbOutput
So you need to explicitly insert extra lines
require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s %>
<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h, nil, '<>').result
puts s
This will give:
Starting erbOutput
0
1
2
3
4
Ending erbOutput
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With