1

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?

4

2 回答 2

3

那这个呢?

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

实际上,我String#indent在自己的库中有一个方法,例如:

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

使用它,您可以在各个地方重复使用它。

# layout.html.erb
<body>
<%= yield.indent %>
</body>
于 2013-07-28T09:58:22.697 回答
0

扩展 Sawa 的答案,我发现了一种更灵活的缩进内容的方法。虽然上面 Sawa 的方法工作得很好,但如果您在<%= yield %>.

这是一个可以根据特定需求进行定制的轻微改进:

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

现在您可以直接从布局中指定需要多少缩进空间,如下所示:

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

上面的示例将为您的收益的每一行应用 4 个缩进空格。如果还有其他级别,您会将其更改为 6,依此类推...

于 2013-07-28T13:44:29.847 回答