4

プラグインの場合、次の機能を Rails にハックしたいと考えています。

(部分的な) テンプレートが (形式に関係なく) 存在しない場合、デフォルトのテンプレートをレンダリングしたいと考えています。

したがって、users/index.html.erb (または他の形式) が存在しない場合に「users/index」というアクションを呼び出すと、「default/index.html.erb」がレンダリングされます。

同様に、アクション「locations/edit」を呼び出し、「locations/edit.html.erb」が存在しない場合、「default/edit.html.erb」をレンダリングする必要があります

パーシャルの場合、アクション「locations/index」を呼び出し、テンプレート「locations/index.html.erb」が存在しないパーシャル「locations/_location」を呼び出す場合、「default/_object」をレンダリングする必要があります

解決策はシークで、テンプレート変数 (@users、@locations など) と要求されたパス (users/index、locations/edit など) の情報にアクセスできます。また、パーシャルでも動作するはずです。

以下に投稿するいくつかのオプションを考えました。どれも完全に満足できるものではありません。

4

4 に答える 4

12

解決策 2:

ApplicationController で「rescue_from」を使用する


class ApplicationController > ActionController::Base
  rescue_from ActionView::MissingTemplate do |exception|
    # use exception.path to extract the path information
    # This does not work for partials
  end
end



欠点: パーシャルでは機能しません。

于 2009-05-12T09:12:10.690 に答える
3

Rails 3.1 は、controller/template.html.erb を調べた後、application/template.html.erb 内のファイルを自動的に探します。これは、次のように例外で確認できます。

Missing template [controller name]/index, application/index with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:erb, :coffee, :builder]}. Searched in: * "/path/to/rails_project/app/views" 

したがって、デフォルトのテンプレートを app/views/application に配置するだけです

于 2011-09-05T18:18:13.980 に答える
2

比較的きれいなパッチを見つけました。それは、まさに質問で必要とされたテンプレートのルックアップにパッチを当てるだけです。


module ActionView
  class PathSet

    def find_template_with_exception_handling(original_template_path, format = nil, html_fallback = true)
      begin
        find_template_without_exception_handling(original_template_path, format, html_fallback)
      rescue ActionView::MissingTemplate => e
        # Do something with original_template_path, format, html_fallback
        raise e
      end
    end
    alias_method_chain :find_template, :exception_handling

  end
end
于 2009-05-12T15:53:41.987 に答える
0

解決策 1:

モンキーパッチ ActionView::Base#render


module ActionView
  class Base
    def render_with_template_missing(*args, &block)
      # do something if template does not exist

      render_without_template_missing(*args, &block)
    end
    alias_method_chain :render, :template_missing
  end
end

このモンキー パッチでは、レールの (変化する) 内部構造を調べる必要があり、醜いコードになりますが、おそらく機能します。

于 2009-05-12T09:08:16.157 に答える