如何创建HTML标记并将其放在帮助器中带有content_tag的现有HTML标记中?

时间:2016-09-13 05:00:41

标签: ruby-on-rails ruby-on-rails-5

我有@profile has_many positions。 HTML版本如下所示:

<h3>Defensive Midfield</h3>
<div class="alternative-positions">
  <small>Attacking Midfield</small><br />
  <small>Right Midfield</small>
</div>

但是,我正在做的是创建一个帮助来抽象这个视图逻辑,所以我在content_tags中放了一堆profile_helper.rb

规则如下:

  1. 当个人资料只有1个位置时,它会进入h3标记。
  2. 当有2时,第一个进入h3,第二个进入small div.alternative-positions
  3. 当有3时,请按照#1&amp; #2然后将第三个位置放在现有<small>内新创建的div.alternative-positions内。
  4. 1&amp; 2很简单,我可以用这段代码做到这一点:

      def player_positions(profile)
        profile.positions.each_with_index do |index, position|
          if index == 0
            content_tag(:h3, position.position_type)
          else
            content_tag(:div, content_tag(:small, position.position_type), class: "alternative-positions")
          end
        end
      end
    

    在我的观点中称之为:

    <%= player_positions(@profile) %>
    

    然而,我正在努力解决的问题是第三个问题。

    我不太确定如何选择该div,并确保新创建的small标记和内容嵌套在现有div中。

    我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

我建议单独处理列表中的第一个(即不是每个条款的一部分),例如:

def player_positions(profile)
  position_str = ""
  position_str << content_tag(:h3, profile.positions.first.position_type) if profile.positions.size >= 1
  if profile.positions.size >= 2
    # this is the surrounding div for all other positions
    position_str << "<div class='alternative-positions'>"
    profile.positions[1..-1].each_with_index do |index, position|
      position_str << content_tag(:small, position.position_type)
    end
    position_str << "</div>"
  end
  position_str
end

或类似(注意:未检查拼写错误或错误)