8

レイアウト内から現在レンダリングされているビューの名前を取得することは可能ですか?

4

6 に答える 6

4

現在のビューの完全なファイル パスを取得するために使用しますが、ヘルパーを記述せずにファイル自体<% __FILE__ %>からのみ使用できます

于 2014-05-19T23:03:11.550 に答える
3

メソッド active_template_virtual_path メソッドは、テンプレートを次の形式の名前として「コントローラー/アクション」として返します。

 class ActionController::Base
  attr_accessor :active_template

  def active_template_virtual_path
    self.active_template.virtual_path if self.active_template
  end
end

class ActionView::TemplateRenderer 

  alias_method :_render_template_original, :render_template

  def render_template(template, layout_name = nil, locals = {})

    @view.controller.active_template = template if @view.controller
    result = _render_template_original( template, layout_name, locals)
    @view.controller.active_template = nil if @view.controller
    return result

  end
end
于 2012-07-12T10:57:36.387 に答える
1

同様の質問がありました。body タグにコントローラー名とアクション名をクラスとして追加する必要がありまし<%= params[:controller] %>た。<%= params[:action] %>

それが誰かを助ける場合に備えて。:)

于 2014-03-01T17:07:45.573 に答える
1

現在、Peter Ehrlich のソリューションの修正版を使用しています。controller_name/view_name結果の文字列は、たとえばの形式になります。これは、後でusers/new直接渡すことも、他の用途に合わせて変更することもできることを意味します。renderこれは Rails 4.2 でしか試していませんが、私の知る限りでは、3.x にまでさかのぼって動作するはずです

ActionView::Base.class_eval do
  attr_accessor :current_template
end

ActionView::TemplateRenderer.class_eval do
  def render_template_with_current_template_accessor(template, layout_name = nil, locals = {})
    @view.current_template = template.try(:virtual_path)
    render_template_without_current_template_accessor(template, layout_name, locals)
  end

  alias_method_chain :render_template, :current_template_accessor
end
于 2015-01-26T02:08:00.170 に答える