Search code examples
nestedsyntax-errorlink-tocontent-tagrails7

Nested <span> tag inside link_to in Rails 7


I need the following HTML output exactly as shown below:

<section id='option1'>
  <a href='#option1'><h6>Option1</h6><span>&#x3e;</span></a>
  <div class='content'>Option1 content...</div>
</section>

I am using a Ruby block to create multiple sections like the one shown above in order to build an accordion UI. However, the problem is that the <span> tag won't nest inside the <a> tag properly. I have checked out other SO queries on the subject, but can't seem to find a solution.

What I hope to end up with is a Ruby block that looks something like this:

  <% %w[option1 option2].each do |act| %>
    <%= tag.section do %>
      <%= link_to("#{act}".capitalize, "##{act}", {class: 'centered', data: { turbo_frame:"content"}}) do %>
        <%= tag.h6 act do %>
          <%= tag.span raw "&#x3e;" %>
        <% end %>
      <% end %>
    <% end %>
  <% end %>

But I get a undefined method 'stringify_keys' for "option1":String

Can someone help me construct a nested content_tag that puts all the required elements in the right place?


Solution

  • Ok, so with some fiddling with the HTML structure, I came up with the following that works:

    <div id='accordion'>
      <% %w[option1 option2 ... optionN].each do |act| %>
        <%= tag.h2(id:"accordion_header", class: "ui-accordion-header") do %>
          <%= link_to("#{act}".capitalize, "#{act}") %>
        <% end %>
        <%= tag.div(id: "#{act}", class: "ui-accordion-content") do %>
          <%= render "/sidebars/content/#{controller_name}/#{act}", formats: :html, handlers: :erb %>
        <% end %>
      <% end %>
    </div>
    <script>
      $("#accordion").accordion();
    </script>
    

    I still haven't figured out how to get the anchor tags to respond to the click event and render the appropriate content via turbo-frames yet, so feel free to comment on how to do that. The documentation for Turbo is (at the present) woefully inadequate.