gpt4 book ai didi

ruby-on-rails - rails 渲染集合嵌套部分

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:50 25 4
gpt4 key购买 nike

我正在尝试使用 Rails 渲染一个集合。当遵循 Rails 指南的 section on the topic 时,这看起来是一个简单的操作.

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

所以按照这个建议我声明

<%= render partial: "comments/comment", collection: @post.comments %>

在部分 views/comments/_comment.html.erb 中,我有以下内容

<div="comment_wrapper">
<p class="comment_name"><%= comment.name %></p>
<p class="comment_date"><%= comment.created_at %></p>
<p class="comment_body"><%= comment.body %></p>
</div>

现在,不知何故,所有这些部分都相互嵌套了。所以假设我有 2 条评论,那么它会像这样呈现

<div="comment_wrapper">
<p class="comment_name"><%= comment.name %></p>
<p class="comment_date"><%= comment.created_at %></p>
<p class="comment_body"><%= comment.body %></p>
<div="comment_wrapper">
<p class="comment_name"><%= comment.name %></p>
<p class="comment_date"><%= comment.created_at %></p>
<p class="comment_body"><%= comment.body %></p>
</div>
</div>

有人知道为什么会这样吗?以及如何预防?提前致谢

最佳答案

事实上,他们没有。

这只是您的浏览器试图理解无效的 HTML 以构建可显示的 DOM。

<div="comment_wrapper">

这是无效的。标签具有可以为其分配值的属性。我猜这是关于 CSS(所以属性是 idclass)并且页面上显然不止一次出现这种情况(只留下 class):

<div class="comment_wrapper">

还有...

如果您在编写纯 HTML 时遇到困难,您可以切换到一些模板语言,例如 SlimHaml这可能会因无效代码而出错,或者产生出乎意料的结果,以至于错误很明显。但是,了解底层语言 (HTML) 有助于自信地构建标记。最重要的是,天哪,这是一门额外的语言!以下是您在 Slim 中的部分外观:

.comment_wrapper
p.comment_name= comment.name
p.comment_date= comment.created_at
p.comment_body= comment.body

考虑一下,如果这对您来说太过分了,请随时留在 ERB。

关于ruby-on-rails - rails 渲染集合嵌套部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com