I have created content type XXX, via views I collected all titles of XXX content. That all titles works as links, I want to add active class to title which was clicked in block. It should works as menu item.
2 Answers
If you are generating a menu structure, I would suggest the following:
Your view should use the HTML List format. In the settings use the unordered list type. You probably should add a list class setting like nav (or your theme's default class for nav elements).
The Format Show type should be Fields. In the settings, uncheck the "Provide default field wrapper..." option.
The results should be a straight forward ul list with li wrapped anchors. E.g.
<ul class="nav">
<li>
<a href='node/1'>Node Title</a>
</li>
// other titles below
</ul>
Standard menu CSS should work on this, e.g .nav > li > a to select anchors and the like.
If you still need a css class on the label, you can add a hidden path field above the title. Remove the link to content option. Then rewrite the title field with something like:
<a href='{{ path }}' class='foo'>{{ title }}</a>
To get an active class, you have several options.
If you are using a bootstrap based theme, you can just add the appropriate bootstrap classes to this since it's a simple ul structure. See the bootstratp docs for more details.
It is easy to add a bit of jQuery script to do this. See this for some sample code.
Or you can do it with the template_preprocess_views_view_field() hook. Here's some sample code for that. You will probably have to dump the output value to see how it is layed out. Note that you will have to play some games with getting the current path into the same format, especially if you are using path aliases. Some sample code.
-
Thank you for your answer. Is this will add active class to clicked title? or just "foo" class ?– EviCommented Jan 11, 2018 at 9:40
-
I want for Drupal 8 something like drupal.stackexchange.com/questions/224780/…– EviCommented Jan 11, 2018 at 9:44
-
-
1
There is a patch in the Drupal core issue queue to fix this: https://www.drupal.org/project/drupal/issues/2652000