ruby on rails - How do I create an HTML tag and place it within an existing HTML tag with content_tag in a helper? -


i have @profile has_many positions. html version looks this:

<h3>defensive midfield</h3> <div class="alternative-positions">   <small>attacking midfield</small><br />   <small>right midfield</small> </div> 

however, doing creating helper abstract view logic, putting bunch of content_tags in profile_helper.rb.

the rules follows:

  1. when profile has 1 position, goes h3 tag.
  2. when there 2, first 1 goes h3, , second goes small in div.alternative-positions.
  3. when there 3, follow #1 & #2 put third position within newly created <small> within existing div.alternative-positions.

1 & 2 straightforward , can code:

  def player_positions(profile)     profile.positions.each_with_index |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 

which called in view so:

<%= player_positions(@profile) %> 

however, issue struggling 3rd one.

i not quite sure how select div, , make sure newly created small tag , content nested within existing div.

how achieve that?

i'd recommend treating first in list separately (ie not being part of each clause) eg:

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     # surrounding div other positions     position_str << "<div class='alternative-positions'>"     profile.positions[1..-1].each_with_index |index, position|       position_str << content_tag(:small, position.position_type)     end     position_str << "</div>"   end   position_str end 

or similar (note: not checked typos or bugs)


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -