2016-05-23 25 views
0

我提到的ERB庫是ERB是否可以使用ERB庫評估html.erb模板中的yield語句?

require 'ERB' 
simple_template = "Statement: <%= yield %>." 
renderer = ERB.new(simple_template) 

我希望能夠在一個塊通過在yield語句中使用simple_template。有沒有辦法與ERB圖書館做到這一點?

下不起作用:

renderer.result { "I am yielded" } # LocalJumpError: no block given (yield) 

也不對:

prc = Proc.new { "I am yielded" } 
renderer.result(prc) # TypeError: wrong argument type proc (expected binding) 

是否有更好的方法來做到這一點比使用ERB庫?

這個問題似乎是指在application.html.erb中的Rails應用程序中發生了什麼。

更新: 這裏有問題,重複我發現: yield in ERB without rails

+0

你只是想執行exec ute邏輯並將其保存在您的視圖文件中? –

+0

我試圖實際實現我自己的(更基本的)版本的Rails web框架,並且涉及渲染由基本的application.html.erb類型視圖和插入到yield語句中的另一個視圖組成的視圖。 – evianpring

回答

1

你需要其中創建Binding,你會與模板使用傳給你想上下文塊:

require 'erb' 


def render(name) 
    TEMPLATE.result(binding) 
end 

render('evianpring') { 'blocks' } 
# => "evianpring yields to the power of blocks!" 

讓我們來深入探討它的工作原理。從綁定文檔:

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained.

那麼在綁定的執行上下文中有什麼可用創建在這裏?

def render(name) 
    TEMPLATE.result(binding) 
end 
  • 本地#render()name
  • TEMPLATE
  • 任何全局變量,如果我們想用產量將需要通過我們傳遞給#render()

因此,任何阻止任何變量塊到#render()

+0

有關綁定的文檔沒有多說關於如何使用它的塊(http://ruby-doc.org/core-2.2.0/Binding.html)。爲什麼這不起作用(假設你在之前的某個地方定義了變量名):TEMPLATE.result(binding {「blocks」})。這會產生一個LocalJumpError:沒有給出的塊(yield)。這是一件有約束力的事情,或者我錯過了將一個產量放在塊內的Ruby事情? – evianpring

+0

我其實犯了一個錯誤。我原先在那裏的收益電話是多餘的。 – fny