如何为Rails的部分渲染查找添加视图路径? [英] How can I add a view path to Rails's partial rendering lookup?

查看:145
本文介绍了如何为Rails的部分渲染查找添加视图路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望具有以下目录结构:

I'd like to have the following directory structure:

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目录,然后检入共享目录,然后再引发丢失模板错误?

So basically, how do I tell Rails to check in the /app2/users dir then the shared dir before it raises it's missing template error?

我解决了这个问题(如Senthil所建议,使用File.exist?

I got around this (as suggested by Senthil, using File.exist?

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

Here's my solution - feedback and suggestions welcome

# 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

推荐答案

在Rails中已经内置了一些东西,可以帮助您实现这种主题化".它称为 prepend_view_path .

There's already something built into rails that facilitates this type of "theming" for you. It's called prepend_view_path.

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

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

There's also append_view_path for adding paths to the end of the lookup stack.

我已经在生产中成功完成了这项工作:

I have this successfully working in production:

 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"(或您的动态名称为)中查找与所调用操作相对应的视图.

Now every controller will first look in "views/app1" (or whatever your dynamic name turns out to be) for the views corresponding to the action being called.

它还很智能,可以检查要查找的文件的所有定义的路径,因此如果找不到该文件,它会回滚到默认位置.

It's also smart enough to check all the defined paths for the file you're looking for, so it rolls back to the default location if one isn't found.

这篇关于如何为Rails的部分渲染查找添加视图路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆