Add class for active tag

Hi,

I have a tag snipet with the following code :slight_smile:

<?php
$tags = $page->children()->visible()->pluck('tags', ',', true);
if($tags): ?>

  <div class="filter">
  <hr>
    <h3>Par Thème</h3>
    <ul>
      <li class="inbl"><a href="<?php echo $page->url() ?>"><button class= "btn plain">← Tous</button></a></li>
      <?php foreach($tags as $tag): ?>
        <li class="inbl">
          <a href="<?php echo $page->url() . '/' . $tag ?>">
            <button <?php e($tag == $tagged, 'class="btn special"') ?>><?php echo $tag ?></button>
          </a>
        </li>
      <?php endforeach ?>
    </ul>
    <?php endif ?>
  </div>
</div>

I works well but when I have added the code part
<?php e($tag == $tagged, 'class="btn special"') ?>
to have class special on the current tag, sometimes it works, sometimes I get an error
Undefined variable: tagged
It seems that the error is coming randomly and I have difficulties to identify the issue.
Even tough some posts in the forum address similar issues I didn’t succeed to solve my own problem.
Thanks for any help

Where did you define $tagged. Maybe I’m foolish, maybe I’m blind, but I can’t see it anywhere?

You should have something like:

<?php 
$tagged = kirby()->request()->params()->tag();

or

<?php
$tagged = param('tag');

somewhere…

Actually in the controller I have the following code where tagged is defined as
$tagged = urldecode($data['tag']);

<?php

    return function ($site, $pages, $page, $data) {
        $children = $page->children()->visible();
        if (isset($data['tag'])) {
          $tagged = urldecode($data['tag']);
          $children = $children->filterBy('tags', $tagged, ',');
          if($children->count() == 0){
             go('error');
          }
        }
        return compact('children', 'tagged');
    };
?>

And in the template I have:
<?php snippet('children', array('data' => $children)); ?>

Is it enough ?

Well, the problem with your code is that $tagged is undefined if $data['tag'] does not exist. Where does $data come from, from a route? In any case, you should set $tagged to empty if the condition is not met.

I add the following code:

<a href="<?php echo $page->url() . '/' . $tag ?>">
  <button <?php if(!empty($tagged)): e($tag == $tagged, 'class="btn special"') ?>
  <?php endif ?>>
  <?php echo $tag ?>
  </button></a>

It seems to work now.
Thank you

16 posts were split to a new topic: Add active class to active param