22

我想要以下目录结构:

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

  app2/
    users/index.html.erb

  shared/
    users/_user.html.erb
    users/index.html.erb

在我看来,我会打电话给

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


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

所以基本上,我如何告诉 Rails 在它引发它缺少模板错误之前检查 /app2/users 目录然后是共享目录?

更新


我解决了这个问题(正如 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
4

1 回答 1

66

Rails 中已经内置了一些东西,可以为您提供这种类型的“主题化”。它被称为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

现在每个控制器将首先在“views/app1”(或任何你的动态名称)中查找与被调用的操作相对应的视图。

它也很聪明,可以检查您要查找的文件的所有已定义路径,因此如果找不到,它会回滚到默认位置。

于 2011-05-21T15:39:49.093 回答