渲染异构集合:如何为部分指定单个目录?
我有一个集合@comments,它是异构但分层的。每个评论要么是 Comment 的实例,要么是某个派生类,例如 ActionComment 或 InactionComment。我正在为每种类型的评论呈现不同的部分。视图代码是:
= render @comments
由于所有部分都是相关的,我想将它们保留在单个视图目录中,即:
- app/views/comments/_comment.haml
- app/views/ comments/_action_comment.haml
- app/views/comments/_inaction_comment.haml
但现在为了使用正确部分的自动渲染,我使用单独的目录,例如:
- app/views/comments/_comment.haml
- app/views/ action_comments/_action_comment.haml
- 应用程序/视图/inaction_comments/_inaction_comment.haml
I have a collection, @comments, that is heterogeneous but hierarchical. Each comment is either an instance of Comment or some derived class, like ActionComment or InactionComment. I am rendering a different partial for each type of Comment. The View code is:
= render @comments
As all the partials are related, I would like to keep them in a single view directory, i.e.:
- app/views/comments/_comment.haml
- app/views/comments/_action_comment.haml
- app/views/comments/_inaction_comment.haml
But right now in order to use the automatic rendering of the correct partial, I am using separate directories, like:
- app/views/comments/_comment.haml
- app/views/action_comments/_action_comment.haml
- app/views/inaction_comments/_inaction_comment.haml
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 3.2 提供了一个 Model#to_partial_path 方法,它允许您(正如其名称所示)覆盖部分路径名。
它返回的路径不包含前导下划线,并假定相对于
.../views/modelname/
。请参阅 http:// /blog.plataformatec.com.br/2012/01/my- Five-favorite-hidden-features-in-rails-3-2/ 了解概述Rails 3.2 makes a Model#to_partial_path method available which allows you (as its name suggests) to override the partial pathname.
The path it returns does not include the leading underscore and is assumed to be relative to
.../views/modelname/
. See http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/ for an overview您无法如此神奇地做到这一点,但您可以通过单独渲染每个项目并指定部分来做到这一点。
Haml 中的示例:
You can't do it quite as magically, but you can do it by just rendering each item individually and specifying the partial.
example in haml: