如何拦截Rails的模板渲染 [英] How can I intercept rails's template rendering

查看:60
本文介绍了如何拦截Rails的模板渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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/

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

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

  • 调用App1的UsersController#index时,它将呈现app1/users/index.html.erb
  • 在调用App2的UsersController#index时,它意识到没有index.html.erb模板,因此在出现丢失的模板错误之前检查一下shared/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}"

将其扔到应用程序控制器中的before_filter中,所有控制器都将遵守:

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

如果"app1"是当前应用,则当请求"/users"时,现在rails将首先查找"app/views/app1/users/index.html.erb".

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

如果在该位置找不到它,它将回滚到默认位置"app/views/users/index.html.erb".

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.

这篇关于如何拦截Rails的模板渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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