Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created June 9, 2016 05:53
Show Gist options
  • Save oddlyfunctional/3174ba6369bb485630d0a9dc174c7350 to your computer and use it in GitHub Desktop.
Save oddlyfunctional/3174ba6369bb485630d0a9dc174c7350 to your computer and use it in GitHub Desktop.
Different ways to apply custom layouts to a controller's actions
# Passing a String to the layout:
class TestsController < ApplicationController
layout "test_layout" # maps to app/views/layout/test_layout.html.[erb/haml/slim/whatever template engine you're using]
# The test_layout is going to be applied here...
def index
end
# ...and here as well
def new
end
end
# Passing a Symbol to the layout:
class TestsController < ApplicationController
# Is going to run the my_custom_method when it needs to
# define the layout for the current view.
# It's useful for defining the layout dynamically, for
# example when it depends on some parameter or on the user's role.
layout :my_custom_method
# Is going to render whatever layout is returned by my_custom_method
def index
end
# Here too!
def new
end
# It's a good practice to use the private visibility for methods that are not actions in controllers.
private
def my_custom_method
if current_user.admin? # chooses the layout according to the user role in the application
"admin_layout"
else
"customer_layout"
end
end
end
# Setting an action-dependent layout:
class TestsController < ApplicationController
# This action is going to use the app/views/layouts/test_layout.html.erb layout
def index
# Don't pass a Symbol here (render layout: :test_layout),
# is not going to map to a method as in the previous example,
# but raise an ArgumentError exception with the following message:
# String, Proc, :default, true, or false, expected for `layout'; you passed :test_layout
render layout: "test_layout"
end
# This action is going to use the app/views/layouts/application.html.erb layout
def new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment