如何拦截rails的模板渲染

发布于 2024-11-08 01:52:05 字数 414 浏览 1 评论 0原文

我有一个为多个网站提供服务的应用程序。 与 Stack Exchange 类似,这几个站点的行为非常相似。

给定以下视图目录结构:

views/
  shared/users/index.html.erb
  app1/users/index.html.erb
  app2/users/

如何在Rails中重写默认模板渲染,以便

  • 当调用App1的UsersController#index时,它渲染app1/users/index.html.erb,
  • 当调用App2的UsersController#index时,它实现没有index.html.erb模板,因此在引发丢失模板错误之前检查shared/users/index.html.erb

提前致谢

I have an application which serves more than one website.
Similar to Stack Exchange, these several sites behave very similarly to each other.

Given the following views directory structure:

views/
  shared/users/index.html.erb
  app1/users/index.html.erb
  app2/users/

How can I re-write the default template rendering in Rails so that

  • when App1's UsersController#index is called, it renders app1/users/index.html.erb
  • when App2's UsersController#index is called, it realises there is no index.html.erb template so for checks shared/users/index.html.erb before raising the missing template error

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何时共饮酒 2024-11-15 01:52:05

我知道您已经接受了这个问题的答案,但我认为您不需要创建自己的模板解析器。

如果我正确理解你的问题,那么你正在尝试根据应用程序当前状态的某些方面来“主题化”你的观点。我之前使用这个花哨的小控制器方法做了同样的事情:

prepend_view_path "app/views/#{current_app_code}"

将其放入应用程序控制器中的 before_filter 中,所有控制器都会服从:

class ApplicationController < ActionController::Base
  before_filter :prepend_view_paths

  def prepend_view_paths
    prepend_view_path "app/views/#{current_app_code}"
  end

end

现在,rails 将首先查找“app/views/app1/users/index.html”。如果“app1”是当前应用程序,则在请求“/users”时显示“erb”。

如果在那里找不到它,它将回滚到“app/views/users/index.html.erb”的默认位置。

希望这能为您提供另一种选择。

I know you already accepted an answer for this, but I don't think you need to create your own template resolver.

If I understand your question correctly, you are trying to "theme" your views depending on some aspect of the current state of the app. I have done the same thing previously using this dandy little controller method:

prepend_view_path "app/views/#{current_app_code}"

Throw this in a before_filter in your application controller, and all your controllers will obey:

class ApplicationController < ActionController::Base
  before_filter :prepend_view_paths

  def prepend_view_paths
    prepend_view_path "app/views/#{current_app_code}"
  end

end

Now rails will first look for "app/views/app1/users/index.html.erb" when "/users" is requested if "app1" is the current app.

If it doesn't find it there, it rolls back to the default location at "app/views/users/index.html.erb".

Hope this gives you another alternative.

山有枢 2024-11-15 01:52:05

我相信您必须编写自己的模板解析器。
也许这篇博文 可以提供帮助。

I believe that you'll have to code your own Template Resolver.
Perhaps this blog post can help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文