Home > Blockchain >  Insert dynamic class assignment to a Rails link_to tag
Insert dynamic class assignment to a Rails link_to tag

Time:08-02

I am trying to add a dynamic class to a link_to in Rails 7. I have the following code, but it's not inserting the appropriate content based on the request.env["PATH_INFO"]...

<ul>
        <% %w[blog headlines network].each do |nav_link| %>
        <%= added_class = request.env["PATH_INFO"] == nav_link ? "nav_current" : nil %>
          <li ><%= link_to "#{nav_link}".capitalize, "/#{nav_link}", id: "nav_main", class: "btn btn_nav #{added_class}" %></li>
        <% end %>
      </ul>

However, the resulting HTML is:

      <ul>
          <li ><a id="nav_main"  href="/blog">Bog</a></li>
          <li ><a id="nav_main"  href="/headlines">Headlines</a></li>
          <li ><a id="nav_main"  href="/network">Network</a></li>
      </ul>

As you can see, the added_class doesn't get inserted. Any ideas?

CodePudding user response:

request.env['PATH_INFO'] contains a leading / (at least on Rails 7; and IIRC on previous versions as well)

That means that if you are visiting localhost:3000/blog, request.env['PATH_INFO'] is /blog, not blog.

The following code should fix it:

<ul>
  <% %w[blog headlines network].each do |nav_link| %>
    <% added_class = request.env["PATH_INFO"] == "/#{nav_link}" ? "nav_current" : nil %>
    <li ><%= link_to "#{nav_link}".capitalize, "/#{nav_link}", id: "nav_main", class: "btn btn_nav #{added_class}" %></li>
  <% end %>
</ul>

CodePudding user response:

Ok, so the following code does what I wanted it to. It injects a custom class into the link tag so that I can track the current button and style it differently... :

      <ul>
        <% %w[blog headlines network].each do |nav_link| %>
        <% add_class = request.env['PATH_INFO'] == "/#{nav_link}" ? "nav_current" : "" %>
          <li ><%= link_to "#{nav_link}".capitalize, "/#{nav_link}", id: "nav_main", class: "btn btn_nav #{add_class}" %></li>
        <% end %>
      </ul>

No Javascript necessary.

  • Related