Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement erb partials in a non rails app?

Tags:

ruby

erb

partials

I want to do something like this:

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

But how can I use partials in template.erb?

like image 583
bluegray Avatar asked Mar 23 '12 14:03

bluegray


2 Answers

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)
like image 98
Reed Sandberg Avatar answered Nov 18 '22 20:11

Reed Sandberg


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.

like image 34
Jeff B. Avatar answered Nov 18 '22 22:11

Jeff B.