Add active class on 'show all' filter list

Hi,

In order to filter articles on the blog, I have a list of tags. I also added an ‘all’ link that links to the blog page (without a tag filter in de url).

When a tag is active, the class=“active” is added. But how can i do the same in case the ‘all’ link is active? Also: in case there is a cleaner way to code the ‘all’ link, i would like to know.


Controller:

<?php

return function($page) {

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

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

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

// apply pagination
$articles   = $articles->paginate(8);
$pagination = $articles->pagination();

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

};

Template:

<ul class="tags">
  <li><a href="<?= page('blog')->url() ?>">all</a></li>
  <?php foreach($tags as $tag): ?>
    <li <?= param('tag') == $tag ? 'class="active"' : '' ?>>
      <a href="<?= url($page->url(), ['params' => ['tag' => $tag]]) ?>">
        <?= html($tag) ?>
      </a>
    </li>
  <?php endforeach ?>
</ul>

Since you are actually on the blog page anyway, you can use $page->url() instead of page('blog')->url().

As regards the active class, you can either check if param('tag') === '' or empty(params().

Thx but i can’t get it to work. What am i missing?

<ul class="tags">
  <li <?= param('tag') === '' ? 'class="active"' : '' ?>><a href="<?= $page->url() ?>">all</a></li>
  <?php foreach($tags as $tag): ?>
    <li <?= param('tag') == $tag ? 'class="active"' : '' ?>>
      <a href="<?= url($page->url(), ['params' => ['tag' => $tag]]) ?>">
        <?= html($tag) ?>
      </a>
    </li>
  <?php endforeach ?>
</ul>

Ok, param('tag') returns null if the param is not set, so

  <li <?= param('tag') === null ? 'class="active"' : '' ?>><a href="<?= $page->url() ?>">all</a></li>
1 Like

Great! It works.