Rails 4 - Name Of Current Layout?

后端 未结 3 741
我在风中等你
我在风中等你 2021-02-14 01:20

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 incl

3条回答
  •  没有蜡笔的小新
    2021-02-14 01:45

    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
    

提交回复
热议问题