Rails 4 - Name Of Current Layout?

后端 未结 3 668
我在风中等你
我在风中等你 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:43

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-14 01:50

    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
    
    0 讨论(0)
提交回复
热议问题