2012-03-23 56 views
7

我想要做這樣的事情:如何在non rails應用程序中實現erb partials?

require 'erb' 
@var = 'test' 
template = ERB.new File.new("template.erb").read 
rendered = template.result(binding()) 

但我怎麼能在template.erb使用諧音?

+0

http://stackoverflow.com/a/2467313/772874可能的重複您需要'ActionView'。 – 2012-03-23 14:47:53

回答

6

也許蠻力吧?

header_partial = ERB.new(File.new("header_partial.erb").read).result(binding) 
footer_partial = ERB.new(File.new("footer_partial.erb").read).result(binding) 

template = ERB.new <<-EOF 
    <%= header_partial %> 
    Body content... 
    <%= footer_partial %> 
EOF 
puts template.result(binding) 
+0

謝謝!這正是我想到的;) – bluegray 2012-07-04 07:36:38

+0

有沒有一些寶石可以幫助? – Kirby 2017-02-28 16:50:42

1

試圖找出同樣的事情,並沒有找到太多這是滿足比使用Tilt gem,它包裝ERB和其他模板系統等,並支持傳輸塊(又名,獨立的渲染結果呼叫),這可能會更好一點。在Ruby通話

template = Tilt::ERBTemplate.new("layout.erb") 

File.open "other_template.html" do |file| 
    file.write template.render(context) { 
     Tilt::ERBTemplate.new("other_template.erb").render 
    } 
end 

這將other_template的結果應用到yieldhttps://code.tutsplus.com/tutorials/ruby-for-newbies-the-tilt-gem--net-20027

layout.erb

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" /> 
    <title><%= title %></title> 
</head> 
<body> 
    <%= yield %> 
</body> 
</html> 

然後:

上看到。

相關問題