htmlruby-on-railsrubyerubyerubis

How are elements in an eRubis document cloned throughout the page?


I have a simple eRubis (*.html.erb) document, and want to "copy" various elements throughout a page. Whenever I use simple Ruby statements like this: <%= 3.times do %> ... <% end %> with multiple "times" statements within that to copy more elements returns either errors or horribly rendered elements. What is the best way to "copy" multiple elements throughout a eRubis page using Ruby statements?


Solution

  • One approach I use in RoR is content_for and yield. I store my element(s) in a content_for and then I litter yields around wherever I want that element:

    <% content_for :some_elements do %>
      <divs or whatever />
      <and maybe some things too />
      <%= even some more erb %>
    <% end %>
    
    <%= yield :some_elements %>
    <%= yield :some_elements %>
    <%= yield :some_elements %>
    

    Those yields can go anywhere, you could even have the content_for in your layout file and put those yields in any view or partial as many times as you want.

    If you want to simply mock up a list or something, times works perfectly well if you use it correctly:

    <ul>
      <% 10.times do |i| %>
        <li id="item_#{i}">
          content in item <%= i %>
        </li>
      <% end %>
    </ul>
    

    But of course the times approach requires that all the elements be in the same spot. That's the advantage of the content_for/yield way, you can place the yields where ever you want. You can even put a yield inside a times:

    <% 10.times do |i| %>
      <%= yield :some_elements %>
    <% end %>
    

    But that's just crazy. Anyway, have fun.