2012-03-23 63 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> 

然后:

上看到。

相关问题