Rails 4 - The name of the current layout?

I found many resources for Rails 3, but none of Rails 4:


To hold DRY stuff, we have a method that defines some meta tags. I would like to include the layout in the title parameter:

  #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 that I don’t know how to return the current layout in Rails 4 - any help would be greatly appreciated!

+9
ruby-on-rails ruby-on-rails-4
source share
3 answers

In Rails 5, the code:

 controller.send :_layout, ["some_string_here"] 

I don’t know why a string in an array is needed, but what made me work. Our auxiliary file is as follows:

 def current_layout layout = controller.send :_layout, ["test"] return layout.inspect.split("/").last.gsub(/.haml/,"") end 
+10
source share

You can add the following helper method to ApplicationHelper :

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

And you can call it appropriately in the 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 name of the layout with its relative path.

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

.gsub(/.html.erb/) removes part of the layout extension. You may need to configure extension based on your template engine, for example. In the case of using Haml .html.haml .


My decision

From the chat with Kirti, it seems that my forgetting to mention that we manually set out the 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 
+6
source share

For me in Rails 6, the current_layout method will look like this

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

I believe an array is a list of formats used. The _layout method is built dynamically, and I'm not sure what it expects in the formats parameter, but I got the desired behavior just with an empty array. I hope this helps.

0
source share

All Articles