如何在 ERB 元素中包含一个 id(或 class)
How to include an id (or class) in an ERB element
我有这段代码用于显示一篇文章的评论,该文章使用 ERB 元素从数据库中获取和显示信息:
<div class="comments">
<h4 class="comment_author">Comment by <%= comment.author_name %></h4>
<p class="comment"><%= comment.body %></p>
</div>
我想以不同的方式格式化 comment.author_name,所以我想在第二行包含一个 ID,例如
<h4 class="comment_author">Comment by <%= comment.author_name, id: "commenter" %></h4>
但是,当我这样做时,我得到以下 error message。
我在过去添加了 classes 和 ids 来形成元素
:class => "name" 语法如下:
<%= f.submit 'Create Article', :class => 'create_new_article_button'%>
但这似乎在这里也不起作用。有没有不同的方法可以将 id 和 classes 添加到非表单 ERB 元素?
提前致谢!
<%= comment.author_name %>
是 不是 tag/element,它只是一个值(我假设的字符串),因此您不能添加 id
属性给它。你可以改为
<h4 class="comment_author">Comment by
<span id="commenter"><%= comment.author_name %></span>
</h4>
或者直接将 id="commenter"
提供给 <h4>
标签并使用它来定位 span
。
It worked earlier because f.submit
refers to a submit button of a form, meaning it was actually an HTML element & hence you could add an id
or a class
to it.
您不能为内容添加 ID。相反,您应该将 ID 添加到包装您的内容的元素。在你的情况下应该是这样的
<h4 class="comment_author" id='commenter'>Comment by <%= comment.author_name %></h4>
这将创建 ID 为 'commenter' 的 h4 元素。
你在这里混淆了
I have added classes and ids in the past to form elements with the
:class => "name" syntax like so:
<%= f.submit 'Create Article', :class => 'create_new_article_button'%>
But that doesn't seem to be working here either.
表单元素将接收 class
具有它的参数之一。检查文档 here 。但是 <%= %>
只会在视图中显示 ruby 代码的最终结果,而不会向 DOM 添加任何 html 内容。请在实施之前仔细阅读文档。
我有这段代码用于显示一篇文章的评论,该文章使用 ERB 元素从数据库中获取和显示信息:
<div class="comments">
<h4 class="comment_author">Comment by <%= comment.author_name %></h4>
<p class="comment"><%= comment.body %></p>
</div>
我想以不同的方式格式化 comment.author_name,所以我想在第二行包含一个 ID,例如
<h4 class="comment_author">Comment by <%= comment.author_name, id: "commenter" %></h4>
但是,当我这样做时,我得到以下 error message。
我在过去添加了 classes 和 ids 来形成元素 :class => "name" 语法如下:
<%= f.submit 'Create Article', :class => 'create_new_article_button'%>
但这似乎在这里也不起作用。有没有不同的方法可以将 id 和 classes 添加到非表单 ERB 元素?
提前致谢!
<%= comment.author_name %>
是 不是 tag/element,它只是一个值(我假设的字符串),因此您不能添加 id
属性给它。你可以改为
<h4 class="comment_author">Comment by
<span id="commenter"><%= comment.author_name %></span>
</h4>
或者直接将 id="commenter"
提供给 <h4>
标签并使用它来定位 span
。
It worked earlier because
f.submit
refers to a submit button of a form, meaning it was actually an HTML element & hence you could add anid
or aclass
to it.
您不能为内容添加 ID。相反,您应该将 ID 添加到包装您的内容的元素。在你的情况下应该是这样的
<h4 class="comment_author" id='commenter'>Comment by <%= comment.author_name %></h4>
这将创建 ID 为 'commenter' 的 h4 元素。
你在这里混淆了
I have added classes and ids in the past to form elements with the :class => "name" syntax like so:
<%= f.submit 'Create Article', :class => 'create_new_article_button'%> But that doesn't seem to be working here either.
表单元素将接收 class
具有它的参数之一。检查文档 here 。但是 <%= %>
只会在视图中显示 ruby 代码的最终结果,而不会向 DOM 添加任何 html 内容。请在实施之前仔细阅读文档。