【问题标题】:How to create condition for html selector with .each Rails如何使用 .each Rails 为 html 选择器创建条件
【发布时间】:2019-09-25 10:40:17
【问题描述】:

Cycle 显示多个复选框和标签。 5 之后,其余复选框应显示在一个 .for-disable 类下。

如何循环执行?

我在 haml 中的 .each 方法:

- @interests.each do |interest|
  %li
    = f.check_box(interest.id)
    = f.label(interest.id, interest.name)

我试过了:

- @interests.each do |interest|
    - if interest.id == 5
      .for-disable
        %li
          = f.check_box(interest.id)
          = f.label(interest.id, interest.name)
    - else
      %li
        = f.check_box(interest.id)
        = f.label(interest.id, interest.name)

但是,正如预期的那样,在这种情况下,'for-disable' 类中只显示一个复选框。

【问题讨论】:

    标签: html ruby-on-rails ruby css-selectors


    【解决方案1】:

    重要提示:将div 添加为ul 的子代是invalid HTML :)

    作为替代方案,您可以在前五个interests 之后添加for-disable 类添加到lis?

    如何使用each_with_index

    - @interests.each_with_index do |interest, index|
      %li{ class: ("for-disable" if index > 4) }
        = f.check_box(interest.id)
        = f.label(interest.id, interest.name)
    

    如果您愿意,也可以使用 tag 助手的替代语法:

    - @interests.each_with_index do |interest, index|
      = tag.li class: ("for-disable" if index > 4) do
        = f.check_box(interest.id)
        = f.label(interest.id, interest.name)
    

    索引从0开始,因此检查是否> 4


    或者,如果您希望前五个之后的所有 interests 在单独的 div 中,您可以使用:

    %ul
      - @interests.first(5) do |interest|
        %li
          = f.check_box(interest.id)
          = f.label(interest.id, interest.name)
    
    .for-disable
      %ul
        - @interests.drop(5) do |interest|
          %li
            = f.check_box(interest.id)
            = f.label(interest.id, interest.name)
    

    既漂亮又干净,应该提供一些东西来做你所追求的 - 让我知道你的进展情况或者如果你有任何问题:)

    【讨论】:

    • 很高兴我能够帮助@РоманОкс - 您最终使用了哪种方法?
    【解决方案2】:

    我为此写了助手。你可以使用这个助手:

    1. 将这些辅助方法添加到 interests_helper.rb 或您想要的任何位置。

      def checkboxes(interests, form)
        container = ''
        for_disable_div = '<div class="for-disable">'
        interests.each do |interest|
          if interest.id > 5
            for_disable_div += checkbox_item(interest, form)
          else
            container += checkbox_item(interest, form)
          end
        end
        sanitize "#{container} #{for_disable_div}</div>"
      end
      
      def checkbox_item(interest, form)
        content_tag :li do
          form.check_box(interest.id)
          form.label(interest.id, interest.name)
        end
      end
      
    2. 在表单中使用它

      = checkboxes(interests, f)
      

    【讨论】:

    • 这还是有UL无效HTML的问题。
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多