【问题标题】:How to append html in collection_check_boxes (Rails 4)如何在 collection_check_boxes (Rails 4) 中附加 html
【发布时间】:2015-12-24 10:19:49
【问题描述】:

我正在尝试遍历记录并生成 html 代码,该代码将创建如下清单:

<%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname) do |cb| %>
  <% cb.label do %>
    <%= cb.check_box + cb.text %>
  <% end %>
<% end %>

此代码按预期生成检查列表项,中间没有中断。但是当我尝试在每个标签之后添加一个&lt;/br&gt; 标签时:

<%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname) do |cb| %>
  <% cb.label do %>
    <%= cb.check_box + cb.text %>
  <% end %>
</br>
<% end %>

标签不会出现在生成的 HTML 中,我只得到 &lt;/br&gt; 标签。有没有办法以另一种方式附加html代码?

谢谢。

【问题讨论】:

    标签: html ruby-on-rails


    【解决方案1】:

    在 Rails 5 中,这是有效的(注意 = cb.label do %>):

    <%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname) do |cb| %>
      <%= cb.label do %>
        <%= cb.check_box + cb.text %>
      <% end %>
      <br/>
    <% end %>
    

    【讨论】:

      【解决方案2】:

      你只得到&lt;br /&gt;标签的原因是帮助器f.collection_check_boxes返回块内的最后一个元素,你可以试试这个:

      <%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname) do |cb| %>
        <% cb.label do %>
          <%= cb.check_box + cb.text %><br />
        <% end %>
      <% end %>
      

      或者你设置一个这样的列表

      <ul>
      <%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname) do |cb| %>
        <% cb.label do %>
          <li><%= cb.check_box + cb.text %></li>
        <% end %>
      <% end %>
      </ul>
      

      【讨论】:

      • 感谢 Abdoo - 第二种方法(使用列表有效)。第一个不起作用,因为中断在
      【解决方案3】:

      另一种将 html 代码附加到表单的方法是使用 input_html 选项:

      <%= f.collection_check_boxes(:user_ids, User.all, :id, :fullname), input_html: { style: "margin-bottom: 20px" } do |cb| %>
        <% cb.label do %>
          <%= cb.check_box + cb.text %>
        <% end %>
      <% end %>
      

      或者使用item_wrapper_class,与here发布的方式类似。

      【讨论】:

        猜你喜欢
        • 2014-09-22
        • 2016-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        相关资源
        最近更新 更多