如何在具有不同别名 MIME 的视图中使用部分?
我为 2 个不同的用户角色使用 2 组不同的视图。 我
Mime::Type.register_alias "text/html", :basic
在控制器中
class SomeController < ApplicationController
def index
# …
respond_to do |format|
format.html # index.html.erb (advance)
format.basic # index.basic.erb
end
end
end
使用 register_alias :在某些情况下,我必须在两个视图中使用相同的代码,然后我会使用部分,但由于 MIME 别名,我必须使用两个相同的部分: my_partial.html.erb 和 my_partial.basic.erb
我认为有一个解决方案可以干燥代码并仅使用部分代码。
你有一些解决方案吗?
谢谢你, 亚历山德罗
Im using 2 different sets of views for 2 different user's roles.
Im using register_alias :
Mime::Type.register_alias "text/html", :basic
in the controller:
class SomeController < ApplicationController
def index
# …
respond_to do |format|
format.html # index.html.erb (advance)
format.basic # index.basic.erb
end
end
end
In some case I have to use the same code in both views, then I would use a Partial, but because of the MIME alias, I have to use 2 identical partials:
my_partial.html.erb and my_partial.basic.erb
I think there is a solution to DRY the code and use only a partial.
Do you have some solutions ?
thank you,
Alessandro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
旧答案:
我可能尝试了 50 种不同的方法,直到找到一次编写部分的正确方法,但这是值得的,因为它非常简单:
在索引视图中,您通常会这样做:
这隐式地被映射到与您请求的 Mime 相对应的部分,因此这意味着有两个部分实现。如果您想要 DRY 部分,只需显式指定格式:
作为此观察的额外好处,如果您的
responds_to
代码块实际上只是根据格式进行切换并且内部没有逻辑,您可以完全删除该代码块,并且事情仍然隐式地工作。Rails 3.2 更新:
Rails 已弃用对上述内容的支持,并且在最新版本的 Rails 中已完全删除支持。以下是从 Rails 3.2 开始的正确方法:
Old Answer:
I probably tried 50 different things until I figured out the right way of writing the partial once, but it was worth it because it's super simple:
Inside your index view, you normally do:
This implicitly gets mapped to the partial corresponding to the Mime you requested, so it implies having two partial implementations. If you want a DRY partial, simply explicitly specify the format:
As an added bonus of this observation, if your
responds_to
block of code is really just to switch based on the format and has no logic inside it, you can entirely remove that block of code and things still work implicitly.Rails 3.2 update:
Rails has deprecated support for the above and support has been completely removed in the latest version of Rails. The following is the correct way as of Rails 3.2: