user1675920
user1675920

Reputation: 41

How can I use views and layouts with Ruby and ERB (not Rails)?

How can I use views and layouts with Ruby and ERB (not Rails)?

Today i'm using this code to render my view:

def render(template_path, context = self)
 template = File.read(template_path)
 ERB.new(template).result(context.get_binding)
end

This works very well, but how can I implement the same function, but to render the template inside a layout? I want to call render_with_layout(template_path, context = self), and so that it will have a default layout.

Upvotes: 1

Views: 7595

Answers (4)

user1675920
user1675920

Reputation: 41

Thanks for all the answers!

I solved it finally by doing this, I hope someone else also can find this code useful:

def render_with_layout(template_path, context = self)
template = File.read(template_path)
render_layout do
  ERB.new(template).result(context.get_binding)
end
end

def render_layout
layout = File.read('views/layouts/app.html.erb')
ERB.new(layout).result(binding)
end

And I call it like this:

def index
@books = Book.all
body = render_with_layout('views/books/index.html.erb')
[200, {}, [body]]
end

Then it will render my view, with the hardcoded (so far) layout..

Upvotes: 3

Sergey Rodionov
Sergey Rodionov

Reputation: 53

If you are using Sinatra so it has a good docimentation and one of the topics it's nested layouts (see Sinatra README)

Also good idea to use special default layout file (layout.haml or layout.erb in your view directory) This file will be always use to render others. This is example for layout.haml:

!!!5
%html
  %head
    ##<LOADING CSS AND JS, TILE, DESC., KEYWORDS>
  %body
    =yield ## THE OTHER LAYOUTS WILL BE DISPALYED HERE
    %footer
      # FOOTER CONTENT

Upvotes: 2

wannabefro
wannabefro

Reputation: 31

If you use the Tilt gem (which I think is what Sinatra uses) you could do something like

template_layout = Tilt::ERBTemplate.new(layout)
template_layout.render { 
  Tilt::ERBTemplate.new(template).render(context.get_binding)
}

Upvotes: 3

Sir l33tname
Sir l33tname

Reputation: 4340

Since you tagged it with Sinatra I assume that you us Sinatra.

By default you view is rendered in your default layout called layout.erb

get "/" do
   erb :index
end

This renders your view index with the default layout.

If you need multiple layouts you can specify them.

get "/foo" do
   erb :index, :layout => :nameofyourlayoutfile
end

* If you don't use Sinatra you may want to borrow the code from there.

Upvotes: 5

Related Questions