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

前端 未结 4 549
闹比i
闹比i 2020-12-20 06:08

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 = sel         


        
相关标签:
4条回答
  • 2020-12-20 06:10

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

    0 讨论(0)
  • 2020-12-20 06:21

    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
    
    0 讨论(0)
  • 2020-12-20 06:25

    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.

    0 讨论(0)
  • 2020-12-20 06:28

    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)
    }
    
    0 讨论(0)
提交回复
热议问题