Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Name Of Current Layout?

I've found numerous resources for Rails 3, but none for Rails 4:


In an effort to keep things DRY, we have a method which defines some meta tags. I'd like to include the layout in the title param:

  #app/controllers/application_controller.rb
  before_action :set_meta_tags

  def set_meta_tags
    title = (layout != "application") ? "#{layout} ::" : false
    set_meta title: "#{layout} #{setting(:site, :title)}", description: setting(:site, :description)
  end

Only problem is I don't know how to return the current layout in Rails 4 - any help will be greatly appreciated!

like image 882
Richard Peck Avatar asked Apr 01 '14 13:04

Richard Peck


3 Answers

For me in Rails 6 the current_layout method would look like this

def current_layout
  self.controller.send :_layout, self.lookup_context, []
end

I believe the array is a list of formats used. The method _layout is build dynamically and I'm not sure what it's expecting in the formats parameter, but I got my desired behaviour with just an empty array Hope this helps.

like image 56
Mirek Sawicz Avatar answered Oct 20 '22 17:10

Mirek Sawicz


In Rails 5, the code is:

controller.send :_layout, ["some_string_here"]

I don't know why it needs a string in the array but that's what got it working for me. Our helper file looks as follows:

def current_layout
  layout = controller.send :_layout, ["test"]
  return layout.inspect.split("/").last.gsub(/.haml/,"")
end
like image 35
Richard Peck Avatar answered Oct 20 '22 17:10

Richard Peck


You can add the following helper method in ApplicationHelper:

def current_layout
     (controller.send :_layout).inspect.split("/").last.gsub(/.html.erb/,"") 
end

And you can call it accordingly in set_meta_tags method. Something like,

  def set_meta_tags
    title = (current_layout != "application") ? "#{current_layout} ::" : false
    set_meta title: "#{layout} #{setting(:site, :title)}", description: setting(:site, :description)
  end

NOTE:

.inspect gives me the layout name with its relative path.

.split("/").last will remove the relative path and returns just the layout name(with extension).

.gsub(/.html.erb/) removes the extension part of layout. You may need to adjust the extension based on the template engine you are using e.g. In case of Haml use .html.haml.


My Solution

From a chat with Kirti, it seems that my forgetting to mention we had manually set out layout was a big deal. This will work if you manually set your layout:

#app/helpers/application_helper.rb
def current_layout
   self.send :_layout
end

def set_meta_tags
    title  = (current_layout != "application") ? "#{current_layout.titleize} :: " : ""
    set_meta title: title + setting(:site, :title), description: setting(:site, :description)
end
like image 7
Kirti Thorat Avatar answered Oct 20 '22 18:10

Kirti Thorat