102

存在しないパーシャルをレンダリングすると、例外が発生します。レンダリングする前にパーシャルが存在するかどうかを確認したいのですが、存在しない場合は別のものをレンダリングします。.erb ファイルで次のコードを実行しましたが、これを行うためのより良い方法があるはずです。

    <% begin %>
      <%= render :partial => "#{dynamic_partial}" %>
    <% rescue ActionView::MissingTemplate %>
      Can't show this data!
    <% end %>
4

8 に答える 8

102

Currently, I'm using the following in my Rails 3/3.1 projects:

lookup_context.find_all('posts/_form').any?

The advantage over other solutions I've seen is that this will look in all view paths instead of just your rails root. This is important to me as I have a lot of rails engines.

This also works in Rails 4.

于 2011-11-18T09:40:06.977 に答える
73

私もこれに苦労していました。これは私が最終的に使用した方法です:

<%= render :partial => "#{dynamic_partial}" rescue nil %>

基本的に、パーシャルが存在しない場合は何もしません。パーシャルが欠落している場合でも、何かを印刷したいと思いましたか?

編集 1:ああ、私は読解力に失敗します。あなたは何か他のものをレンダリングしたいと言いました。その場合、これはどうですか?

<%= render :partial => "#{dynamic_partial}" rescue render :partial => 'partial_that_actually_exists' %>

また

<%= render :partial => "#{dynamic_partial}" rescue "Can't show this data!" %>

編集2:

代替方法: 部分ファイルの存在を確認する:

<%= render :partial => "#{dynamic_partial}" if File.exists?(Rails.root.join("app", "views", params[:controller], "_#{dynamic_partial}.html.erb")) %>
于 2010-08-24T18:06:02.970 に答える
54

ビュー内から、template_exists? 動作しますが、呼び出し規約は単一の部分的な名前文字列では機能せず、代わりに template_exists?(name, prefix, partial) を取ります

パスの部分を確認するには: app/views/posts/_form.html.slim

使用する:

lookup_context.template_exists?("form", "posts", true)
于 2011-08-26T20:21:38.747 に答える
30

Rails 3.2.13 では、コントローラーを使用している場合は、次のように使用できます。

template_exists?("#{dynamic_partial}", _prefixes, true)

template_exists?に委任さlookupcontextれています。AbstractController::ViewPaths

_prefixesコントローラーの継承チェーンのコンテキストを提供します。

trueパーシャルを探しているためです (通常のテンプレートが必要な場合は、この引数を省略できます)。

http://api.rubyonrails.org/classes/ActionView/LookupContext/ViewPaths.html#method-i-template_exists-3F

于 2013-06-08T13:29:20.677 に答える
8

私はこれが答えられており、100万年前のものであることを知っていますが、これが私のためにこれを修正した方法です...

レール 4.2

まず、これをapplication_helper.rbに入れました

  def render_if_exists(path_to_partial)
    render path_to_partial if lookup_context.find_all(path_to_partial,[],true).any?
  end

そして今、呼び出す代わりに

<%= render "#{dynamic_path}" if lookup_context.find_all("#{dynamic_path}",[],true).any? %>

私はただ電話する<%= render_if_exists "#{dynamic_path}" %>

それが役立つことを願っています。(rails3 では試していません)

于 2015-08-05T18:56:57.300 に答える
7

あなた自身のヘルパーはどうですか:

def render_if_exists(path, *args)
  render path, *args
rescue ActionView::MissingTemplate
  nil
end
于 2016-07-07T13:52:37.913 に答える