Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current view name from layout template in Rails?

Is it possible to get the name of the currently rendered view from inside layout?

like image 790
Evgenii Avatar asked Jul 12 '12 09:07

Evgenii


1 Answers

I did something like this for css namespacing:

# config/initializers/action_view.rb
ActionView::TemplateRenderer.class_eval do

  def render_template_with_tracking(template, layout_name = nil, locals = {})
    # with this gsub, we convert a file path /folder1/folder2/subfolder/filename.html.erb to subfolder-filename
    @view.instance_variable_set(:@_rendered_template, template.inspect.gsub(/(\..*)/, '').split('/')[-2..-1].join('-'))
    out = render_template_without_tracking(template, layout_name, locals)
    @view.instance_variable_set(:@_rendered_template, nil)
    return out
  end

  alias_method_chain :render_template, :tracking
end


# application.html.erb
<body class="<%= :@_rendered_template %>" >
like image 58
Peter Ehrlich Avatar answered Sep 24 '22 10:09

Peter Ehrlich