Making ERB behave like PHP

Suraj N. Kurapati

I was surprised to find that ERB’s code embedding tags <% ... %> produce a newline character by default. This was causing many formatting problems in the generated output, so I hacked ERB to not produce any output for its code embedding tags, just like PHP:

require 'erb'

# A version of ERB whose embedding tags behave like those
# of PHP. That is, only <%= ... %> tags produce output,
# whereas <% ... %> tags do *not* produce any output.
class ERB
  alias original_initialize initialize

  def initialize aInput, *aArgs
    # ensure that only <%= ... %> tags generate output
      input = aInput.gsub %r{<%=.*?%>}m do |s|
        if ($' =~ /\r?\n/) == 0
          s << $&

      aArgs[1] = '>'

    original_initialize input, *aArgs

The hack involves setting ERB’s tag trimming mode to ">", which supresses the generation of a newline character after a tag’s closing delimiter, and appending an extra newline to ERB’s value embedding tags <%= ... %> which happen to be at the end of a line.