Adam McArthur
Adam McArthur

Reputation: 980

Indent entire yield output 2 spaces in Ruby on Rails?

For the sake of good looking code, is there some way to add a tab of spacing across the entire layout <%= yield %> in Ruby on Rails? Here's what I mean:

THIS:

# layout.html.erb
<body>
  <%= yield %>
</body>

PLUS THIS:

# page.html.erb
<h1>Test</h1>
<p>Hello, world!</p>

OUTPUTS:

<body>
  <h1>Test</h1>
<p>Hello, world!</p>
</body>

WHAT I REALLY WANT TO OUTPUT:

<body>
  <h1>Test</h1>
  <p>Hello, World!</p>
</body>

I did some research and found that using a minus sign like <%= yield -%> removes indentation, but I couldn't find a way to add it. Any ideas?

Upvotes: 1

Views: 1411

Answers (2)

Adam McArthur
Adam McArthur

Reputation: 980

Expanding upon Sawa's answer, I just found a slightly more flexible approach to indenting content. Whilst Sawa's method above works just fine, it doesn't push out your yield code enough spaces if you're dealing with multiple block levels before your <%= yield %>.

Here's a slight improvement that can be customized to specific needs:

class String
  def indent(spaces)
    num = (" " * spaces)
    gsub(/^/, num)
  end
end

Now you can specify how many spaces of indentation you need right from your layouts like so:

# layout.html.erb
<body>
  <div class="content">
    <%= yield.indent(4) -%>
  </div>
</body>

The above example will apply 4 spaces of indentation to every line of your yield. If there was another level, you would make change it to 6 and so on...

Upvotes: 0

sawa
sawa

Reputation: 168081

What about this?

# layout.html.erb
<body>
<%= yield.gsub(/^/, "  ") %>
</body>

Actually, I have a method String#indent in my own library such as:

class String
  def indent s = "\t"; gsub(/^/, s) end
end

Using this, you can reuse it in various places.

# layout.html.erb
<body>
<%= yield.indent %>
</body>

Upvotes: 3

Related Questions