Erb:how to make less %?

demo.html.erb
<% 3.times do%>
<%=rand%>
<%end%>
it has 6 ‘%’!
how to make less ‘%’ like this?
<%
3.times do
puts rand
end
%>

Another option to look at is StringIO, so that you keep IO-like methods
such as “puts”. You could also wrap _erbout this way:

$ irb --simple-prompt

require ‘erb’
=> true

require ‘stringio’
=> true

ERB.new(<<‘EOS’).result(binding)
<% out = StringIO.new(_erbout) %>
<%
3.times do
out.puts rand
end
%>
EOS
=> “0.761865648122361\n0.792800150151016\n0.683615203721222\n\n”

Haoqi H. wrote:

demo.html.erb
<% 3.times do%>
<%=rand%>
<%end%>
it has 6 ‘%’!
how to make less ‘%’ like this?
<%
3.times do
puts rand
end
%>

Option 1:

<%=
res=""
3.times do
res << “#{rand}\n”
end
res
%>

(and you can make a helper method to abstract out this pattern)

Option 2:

<%
3.times do
_erbout << “#{rand}\n”
end
%>

This is more fragile, as the name of the _erbout variable can be changed
at runtime, and may not be compatible with other ERB implementations
(e.g. erubis)
without specific configuration. See
http://www.kuwata-lab.com/erubis/users-guide.03.html#erbout-enhancer

Option 3:
Use erubis with PrintEnabledEnhancer. See
http://www.kuwata-lab.com/erubis/users-guide.03.html#printenabled-enhancer
I don’t know if this enables “puts” as well as “print”, and it’s an
erubis-specific function.

Option 4:
Ditch ERB entirely and switch to HAML. Your example becomes just:

  • 3.times do
    = rand

You’ll either love HAML or hate it. Personally I love it. My templates
are a fraction of the size they were before, and I never have to worry
about unbalanced XHTML tags or missing ‘end’ on a block.

HTH,

Brian.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs