我想做这样的事情:
require 'erb'
@var = 'test'
template = ERB.new File.new("template.erb").read
rendered = template.result(binding())
但是如何在template.erb中使用partial?
答案 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
正文中。