如何拦截rails的模板渲染
我有一个为多个网站提供服务的应用程序。 与 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道您已经接受了这个问题的答案,但我认为您不需要创建自己的模板解析器。
如果我正确理解你的问题,那么你正在尝试根据应用程序当前状态的某些方面来“主题化”你的观点。我之前使用这个花哨的小控制器方法做了同样的事情:
将其放入应用程序控制器中的 before_filter 中,所有控制器都会服从:
现在,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:
Throw this in a before_filter in your application controller, and all your controllers will obey:
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.
我相信您必须编写自己的模板解析器。
也许这篇博文 可以提供帮助。
I believe that you'll have to code your own Template Resolver.
Perhaps this blog post can help.