在ERB内部进行

时间:2016-08-05 07:05:57

标签: ruby

当我尝试使用普通Ruby在ERB中实现多个content_for块时,我无法理解这里有些奇怪的东西。

这是我的代码:

# helper.rb
require 'erb'

def render(path)
  ERB.new(File.read(path)).result(binding)
end

def content_for(key, &block)
  content_blocks[key.to_sym] = block
end

def yield_content(key)
  content_blocks[key.to_sym].call
end

def content_blocks
  @content_blocks ||= Hash.new
end

模板:

<% #test.html.erb %>
<% content_for :style do %>
  style
<% end %>
<% content_for :body do %>
  body
<% end %>
<% content_for :script do %>
  script
<% end %>

当我打开irb进行测试时,我得到了

irb(main):001:0> require './helper'
=> true
irb(main):002:0> render 'test.html.erb'
=> "\n\n\n"
irb(main):003:0> content_blocks
=> {:style=>#<Proc:0x005645a6de2b18@(erb):2>, :body=>#<Proc:0x005645a6de2aa0@(erb):5>, :script=>#<Proc:0x005645a6de2a28@(erb):8>}
irb(main):004:0> yield_content :script
=> "\n\n\n\n  script\n"
irb(main):005:0> yield_content :style
=> "\n\n\n\n  script\n\n  style\n"

为什么yield_content :script获得\n\n\n前置,为什么yield_content :style获得script\n\n的结果。

1 个答案:

答案 0 :(得分:2)

如果你这样做

_erbout = ''
_erbout.concat "\n"
#test.html.erb
_erbout.concat "\n"
content_for :style do
  _erbout.concat "\n  style\n"
end

然后你可以看到erb编译模板的内容。模板最终看起来像(为便于阅读而格式化)

_erbout

其中_erbout是累积模板输出的缓冲区。 RewriteEngine on RedirectMatch 301 "(/en/nike-air-max|/en/products/nike-air-max|/en/brands/nike)" "/en/brand/nike" 只是一个局部变量,m

当你调用你的procs时,他们都只是附加到同一个缓冲区,该缓冲区已经包含了模板渲染的结果。