Posts Tagged with "erb"
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.
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.