Filtering content with tags issue


#1

Hi everyone,

First post for me so I wanted to say that I really like Kirby!

I have an issue on my new website.

I followed this tutorial (https://getkirby.com/docs/cookbook/tags) to filter blog articles. The filter system works well.
https://drive.google.com/open?id=1-XL9eQpQFGK5FRskS7YINGZo2m3SQgyh

but when I click on a tag all tags disappear except the selected keyword. (it’s ok but it’s a bit weird)
https://drive.google.com/open?id=1cVIhgav2kd7Jgcjw7Mn9mQo8x_QPS5vl

Is there a way to always keep tags visible but add a active class on the active tag?
https://drive.google.com/open?id=1dR4esze16YciHZfrmec-6uiFzwl7TS0N

My code in the controller:
<?php
return function($site, $pages, $page) {

  // fetch the basic set of pages
  $articles = $page->children()->visible()->flip();

  // add the tag filter
  if($tag = param('tag')) {
    $articles = $articles->filterBy('tags', $tag, ',');
  }

  // fetch all tags
  $tags = $articles->pluck('tags', ',', true);

  return compact('articles', 'tags', 'tag');

};

Thank you in advance!

Alexis


#2

The reason why this happens is because you define your $tags variable after the filtering takes place.

That means, if you articles collection is not filtered yet, you get all tags of all the articles, but if your collection is filtered, then you only get the tags of the filtered collection.

To avoid this from happening, move your $tags definition up in your code

 // fetch the basic set of pages
  $articles = $page->children()->visible()->flip();

  // fetch all tags
  $tags = $articles->pluck('tags', ',', true);

  // add the tag filter
  if($tag = param('tag')) {
    $articles = $articles->filterBy('tags', $tag, ',');
  }

The active class must be added where you output the tags.

$activeTag = param('tag');

foreach($tags as $tag):
  if($tag == $activeTag):
     // add class active
  endif;
endforeach;

#3

Wow so fast! It works perfectly!

Thank you so much @texnixe