渲染异构集合:如何为部分指定单个目录?

发布于 2024-10-01 19:13:03 字数 568 浏览 4 评论 0原文

我有一个集合@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夕嗳→ 2024-10-08 19:13:03

Rails 3.2 提供了一个 Model#to_partial_path 方法,它允许您(正如其名称所示)覆盖部分路径名。

  def to_partial_path
    self.action.to_s
  end

它返回的路径不包含前导下划线,并假定相对于 .../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.

  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/. See http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/ for an overview

墨小墨 2024-10-08 19:13:03

您无法如此神奇地做到这一点,但您可以通过单独渲染每个项目并指定部分来做到这一点。

Haml 中的示例:

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

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:

- @comments.each do |c|
  = render :partial => "comments/#{c.class.to_s.underscore}", :locals => {:comment => c}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文