A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Tuesday, April 20, 2010

Suppressing newlines in Ruby ERB documents outside of Rails

In ERB files the standard <% ... %> tag pair will result in a newline being added to the output.

In Rails you can add a minus sign before the closing tag to suppress this:

<% ... -%>

But if you use ERB outside of Rails, this will produce an ERB compile error.

The way to handle this is to leave out the minus signs and instead specify the trim_mode when you create a new ERB object. There are 3 options for this parameter:
    %  enables Ruby code processing for lines beginning with %
<> omit newline for lines starting with <% and ending in %>
> omit newline for lines ending in %>

Setting the trim_mode requires that you also set a safe_level, but this is normally set to 0. So to suppress newlines on all lines with ERB tag pairs create the ERB object like this:
erb = ERB.new(template_file, 0, '>')

This solves the newline issue for me but it would be nicer to have the per-line option available in Rails.

You can also set the global trim_mode in Rails if you want to. in environment.rb:
config.action_view.erb_trim_mode = ">"




 

Archive of Tips