如何在非rails应用程序中实现erb partials?

我想做这样的事情:

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

但是如何在template.erb中使用partials?

也许蛮力呢?

 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) 

试图发现同样的事情并没有找到令人满意的东西,除了使用Tilt gem ,它包装ERB和其他模板系统并支持传递块(也就是单独的渲染调用的结果),这可能是一个好一点。

见: https : //code.tutsplus.com/tutorials/ruby-for-newbies-the-tilt-gem–net-20027

layout.erb

     <%= title %>   <%= yield %>   

然后在你的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的结果应用到yield主体中。