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

时间:2012-03-23 14:22:41

标签: ruby erb partials

我想做这样的事情:

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

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

2 个答案:

答案 0 :(得分:8)

也许蛮力呢?

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)

答案 1 :(得分:1)

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

见: https://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>

然后在你的红宝石电话中

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正文中。