简体   繁体   English

在Ruby on Rails中缩进整个yield输出2个空格?

[英]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? 为了好看的代码,有没有办法在Ruby on Rails中的整个布局<%= yield %>中添加间距选项卡? 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. 我做了一些研究,发现使用像<%= yield -%>这样的减号删除缩进,但我找不到添加它的方法。 Any ideas? 有任何想法吗?

What about this? 那这个呢?

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

Actually, I have a method String#indent in my own library such as: 实际上,我在自己的库中有一个方法String#indent ,例如:

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>

Expanding upon Sawa's answer, I just found a slightly more flexible approach to indenting content. 根据Sawa的回答,我发现了一种稍微灵活的缩进内容的方法。 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 %> . 虽然Sawa的上述方法运行得很好,但是如果你在<%= 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. 上面的示例将为您的每个产量线应用4个缩进空格。 If there was another level, you would make change it to 6 and so on... 如果有另一个级别,你会把它改为6等等......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM