简体   繁体   English

渲染异构集合:如何为局部文件指定一个目录?

[英]Rendering a Heterogeneous Collection: How can I specify a single directory for the partials?

I have a collection, @comments, that is heterogeneous but hierarchical. 我有一个集合@comments,它是异构的但是分层的。 Each comment is either an instance of Comment or some derived class, like ActionComment or InactionComment. 每个注释要么是Comment的实例,要么是某个派生类,例如ActionComment或InactionComment。 I am rendering a different partial for each type of Comment. 我为每种类型的Comment渲染了一个不同的部分。 The View code is: 查看代码是:

= render @comments

As all the partials are related, I would like to keep them in a single view directory, ie: 由于所有部分都相关,因此我想将它们保留在单个视图目录中,即:

  • app/views/comments/_comment.haml 应用程序/视图/评论/ _comment.haml
  • app/views/comments/_action_comment.haml 应用程序/视图/评论/ _action_comment.haml
  • app/views/comments/_inaction_comment.haml 应用程序/视图/评论/ _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 应用程序/视图/评论/ _comment.haml
  • app/views/action_comments/_action_comment.haml 应用程序/视图/ action_comments / _action_comment.haml
  • app/views/inaction_comments/_inaction_comment.haml 应用程序/视图/ inaction_comments / _inaction_comment.haml

Rails 3.2 makes a Model#to_partial_path method available which allows you (as its name suggests) to override the partial pathname. Rails 3.2提供了Model#to_partial_path方法,该方法允许您(顾名思义)覆盖部分路径名。

  def to_partial_path
    self.action.to_s
  end

The path it returns does not include the leading underscore and is assumed to be relative to .../views/modelname/ . 它返回的路径不包括下划线,并且假定是相对于.../views/modelname/ See http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/ for an overview 有关概述,请参见http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/

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: 以haml为例:

- @comments.each do |c|
  = render :partial => "comments/#{c.class.to_s.underscore}", :locals => {:comment => c}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM