How to implement erb partials in a non rails app?

时光总嘲笑我的痴心妄想 提交于 2019-12-03 03:04:42

Perhaps brute-force it?

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)

Was trying to find out the same thing and didn't find much that was satisfying other than using the Tilt gem, which wraps ERB and other templating systems and supports passing blocks (aka, the results of a separate render call) which may be a little nicer.

Seen on: 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>

Then in your ruby call

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

It will apply the results of the other_template into the yield body.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!