views:

53

answers:

4

I'm a beginner to Ruby/Rails, and just generated my first HTML programmatically - kind of exciting-- but when I viewed "page source" from the browser, my HTML had all these additional gaps and messed up the logical indentation:

This code in a View:

<% @states_array.each do |state| %>
  <ul><%= state %></ul>
<% end %>

and this code in my application.html.erb layout: Practice Header

  <div class="text">
    <%= yield %>
  </div>

  <div class="footer">
  </div>

Produced this HTML when I viewed page source for that page:

      <div class="header">
        Practice Header
      </div>

      <div class="text">

  <ul>California</ul>

  <ul>Colorado</ul>

  <ul>Florida</ul>

  <ul>Georgia</ul>

  <ul>New York</ul>

  <ul>North Carolina</ul>

  <ul>North Dakota</ul>

  <ul>Oregon</ul>

      </div>

      <div class="footer">
      </div>

only an extra space occurred after each row, and the logical indentation of where I put the <%= yield %> was lost. Thanks so much for your help in advance.

A: 

You should probably change it to something like:

<ul>
<% @states_array.each do |state| %>
  <li><%= state %></li>
<% end %>
</ul>
Jack
+2  A: 
<% @states_array.each do |state| %>
  <ul><%= state %></ul>
<% end %>

Results in the string "\n<ul>state</ul>\n" for each state in the array. So the output is technically correct. You could use

<% @states_array.each do |state| %><ul><%= state %></ul>
<% end %>

But that's not as easy to read in your code. I've read there is a way to skip the trailing new lines but don't recall the exact method (Update: see @user156011's answer).

But the truth is - it doesn't really matter. HTML is for the browser - don't worry about how it looks. The only time you really need to pay attention is when two tags must exist one after the other without spacing to prevent browsers from injecting default whitespace - like in a series of tags sliced up from a larger image.

Paul Alexander
+1  A: 

You can suppress the trailing newline by closing with a minus sign:

<% some.ruby.statement -%>

If the beauty of your markup really matters to you, look into Haml (http://haml-lang.com/).

Steve Ross
+1  A: 

If you're going for markup readability - Haml has been nothing but a dream for me. In development mode, it outputs gorgeous HTML that is properly indented. It'll switch to "ugly mode" by default when your app is run in production mode, to save on server resources.

However, if you're new to Ruby/Rails, learning a new templating language may not be in your best interest. (Still, I'd argue that if you can learn ERb, you can easily pickup Haml in a day.)

If you're going to stick to ERb, you can use the <%- and -%> will respectively supress leading/trailing whitespace. Which may help in your quest for clean markup.

Best of luck :)
~Robbie

Robbie
Agreed. Use HAML. A lot easier and cleaner.
nathanvda