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

萝らか妹 提交于 2019-11-28 06:27:29

问题


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.


回答1:


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.




回答2:


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)
}



回答3:


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



回答4:


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..



来源:https://stackoverflow.com/questions/25731535/how-can-i-use-views-and-layouts-with-ruby-and-erb-not-rails

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