Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails layouts per action?

People also ask

What are layouts in rails?

In Rails, layouts are pieces that fit together (for example header, footer, menus, etc) to make a complete view. An application may have as many layouts as you want. Rails use convention over configuration to automatically pair up layouts with respective controllers having same name.

How do you use nested layouts rails?

Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.

How can you tell Rails to render without a layout *?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.

What are partials in Rails?

A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.


You can use a method to set the layout.

class MyController < ApplicationController
  layout :resolve_layout

  # ...

  private

  def resolve_layout
    case action_name
    when "new", "create"
      "some_layout"
    when "index"
      "other_layout"
    else
      "application"
    end
  end
end

If you are only selecting between two layouts, you can use :only:

class ProductsController < ApplicationController
   layout "admin", only: [:new, :edit]
end

or

class ProductsController < ApplicationController
   layout "application", only: [:index]
end

You can specify the layout for an individual action using respond_to:

  def foo
    @model = Bar.first
    respond_to do |format|
      format.html {render :layout => 'application'}
    end
  end

You can also specify the layout for action using render:

def foo
  render layout: "application"
end