Rails inline ERb effects on HTML structure

MAR

31

2007

When using Ruby on Rails, ERb (embedded Ruby) is used a LOT in the X/HTML. There are two types of ERb,

An evaluation block:

<% some_code %>

And an output block:

<%= @print_this_variable %>

These blocks are necessary when using Rails, and I've noticed that when I do a 'View Source' (via the Web Developer addon for Firefox, of course), I see a lot of funky spacing and line breaking where the ERb's have been evaluated. Probably fine for most people, but it makes reading the outputted HTML code a hassle.

It turns out that there are really three ways to use the evaluation ERb that can affect your spacing and line-breaking.

Firstly, the output block is used just like you'd expect to use it. If your code says this:

<p>
  Text before ERb.
  <%= "code_goes_here" %>
  Text after ERb
</p>

The resulting HTML will look just like this:

<p>
  Text before ERb.
  code_goes_here
  Text after ERb
</p>

Evaluation block use #1: If you just put a block, it will cause a line break after the block in the HTML, so if you had this in your code:

<p>
  Text before ERb.
  <% some_code %>
  Text after ERb
</p>

The resulting HTML code would look like this:

<p>
  Text before ERb.

  Text after ERb
</p>

Evaluation block use #2: If you add a dash(-) at the end of the block, it will prevent it from adding a line break. So, if your code looks like this:

<p>
  Text before ERb.
  <% some_code -%>
  Text after ERb
</p>

The resulting HTML code would look like this:

<p>
  Text before ERb.
    Text after ERb
</p>

The line break is gone, but the space taken by the block is still there. That leads us to. . .

Evaluation block use #3: If you add a dash(-) at the beginning AND end of the block, it will prevent it from adding a line break AND remove the leading space it would have taken up. So, if your code looks like this:

<p>
  Text before ERb.
  <%- some_code -%>
  Text after ERb
</p>

The resulting HTML code would look like this:

<p>
  Text before ERb.
  Text after ERb
</p>

You'd never know there was a code block there! Is this useful? I don't know... maybe.

Tagged: rails, xhtml, erb


Jonzo said on July 25, 2007:

The only place I've found it useful is in ActionMailer when generating text emails :-P Other than that it is useful for people who care about other people looking at their code... maybe? Then again! If you don't worry about keepin it tidy your code will look crazy, which will be difficult to understand, which could be form of obfuscation! We never should have doubted you rails, it's obviously a feature!

Leave a comment:




©2008 Travis Roberts. All rights reserved.