Stimulus Discourse

Menu category cached by Rails, how use active menu

Menu category cached by Rails, How to use stimulus to activate css class ?? Thanks!

I’m having to guess what you’re trying to accomplish. :slightly_smiling_face:
…but, assuming Rails has the information regarding what menu should be active, and you want to add a css class to that element so it’s formatted as the active element:

If you’re rendering the category via erb, you could do something like:

<div data-target=".menuCategory"><%= <rails_class>.active_category_id %></div>

… set the target in your controller:

static targets = ["menuCategory’];

…and then in your controller’s connect element, get the information passed and add the active class to it:

const activeCategory = this.menuCategoryTarget.innerText();
document.querySelector("#"+ActiveCategory).classList.add('<my active css class>');

Hello @nikolaokonesh, we ran into the same issue a few months ago.

Feel free to adapt it to your needs. Here are the steps:

  1. Store information about your current page, in our case is App.controller = Users .
  2. Set the value for which the link is marked as active, in our link attributes data-highlight-sidebar-active-on="Users"
  3. Check if the current page makes the link active.

We had to make a few improvements to make them enabled on multiple cases stored as a JSON array. In addition we added some animations with Velocity.

Cheers,
Jeremy.

1 Like

Caching Rails does not give such an opportunity… :worried:

I do no see the issue as connect is called at every navigation and should highlight the correct class.
Be sure to not cache the current page though. In my code I have this at the beginning of the body:

<body>
 <script>
   App.controller = "<%= controller_name %>.<%= action_name %>"
 </script>
...
</body>

The sidebar is cached, and not rendered with a Turbolinks permanent tag so it is not replaced. The active class is responsive to changes of the App.controller at each page change.

1 Like

So good! Thanks everyone! :+1:

with rails

 <script>
   Appcontroller = "<%= request.original_fullpath %>"
 </script>
_category.html.erb
<% cache category do %>
  <%= link_to category_path(category), data: {"controller" => "activelink", "activelink-active-on" => "#{category_path(category)}"} do %>
      <%= sanitize(strip_tags(category.title)) %>
  <% end %>
<% end %>

1 Like