如何为Rails的部分渲染查找添加视图路径?

bod*_*ous 20 ruby-on-rails partial-views actionview actionviewhelper ruby-on-rails-3

我想要以下目录结构:

views/
  app1/
    users/_user.html.erb
    users/index.html.erb

  app2/
    users/index.html.erb

  shared/
    users/_user.html.erb
    users/index.html.erb
Run Code Online (Sandbox Code Playgroud)

在我看来,我打电话

# app1/users/index.html
<%= render :partial => "user" %>
# => /app1/users/_user.html.erb


# app2/users/index.html
<%= render :partial => "user" %>
# => /shared/users/_user.html.erb
Run Code Online (Sandbox Code Playgroud)

所以基本上,如何告诉Rails检查/ app2/users dir然后检查共享目录,然后才会引发它丢失的模板错误?

更新


我绕过了这个(正如Senthil建议的那样,使用 File.exist?

这是我的解决方案 - 欢迎提出反馈和建议

# application_helper.rb

# Checks for a partial in views/[vertical] before checking in views/shared
def partial_or_default(path_name, options={}, &block)
  path_components         = path_name.split("/")
  file_name               = path_components.pop
  vertical_file_path      = File.join(vertical}, path_components, file_name)
  shared_file_path        = File.join("shared", path_components, file_name)
  full_vertical_file_path = File.join("#{Rails.root}/app/views/", "_#{vertical_file_path}.html.erb")
  attempt_file_path       = File.exist?(full_vertical_file_path) ? vertical_file_path : shared_file_path
  render({:partial => attempt_file_path}.merge(options), &block)
end
Run Code Online (Sandbox Code Playgroud)

twm*_*lls 63

已经内置了一些内容,可以为您提供这种"主题".它叫做prepend_view_path.

http://api.rubyonrails.org/classes/ActionView/ViewPaths/ClassMethods.html#method-i-prepend_view_path

还有append_view_path用于将路径添加到查找堆栈的末尾.

我已成功地在生产中工作:

 class ApplicationController < ActionController::Base
   before_filter :prepend_view_paths

   def prepend_view_paths
     prepend_view_path "app/views/#{current_app_code}"
   end
 end
Run Code Online (Sandbox Code Playgroud)

现在,每个控制器将首先查看"views/app1"(或者您的动态名称结果是什么),以查看与被调用动作相对应的视图.

它还足够聪明,可以检查您正在查找的文件的所有已定义路径,因此如果找不到,则会回滚到默认位置.

  • Carson所讨论的类方法是[`AbstractController.prepend_view_path`](http://apidock.com/rails/AbstractController/ViewPaths/ClassMethods/prepend_view_path) (2认同)