I have a list of tags on my site and want to add an active class to the linked tag based on the URL. For example, if the user is on the URL http://whatever.com/blog/by_tag/control+system+failure, I want "Control System Failure" from the list of all tags to have the active class.

I'm using this code:

    <li class="{if '{segment_3}'=='{websafe_tag}'}active{/if}">
         <a href="{path='blog/by_tag'}/{websafe_tag}">{tag}</a>

However, it doesn't work because {segment_3} displays the tag name without the + separator. For example
{websafe_tag} = control+system+failure
{segment_3} = control system failure

I've even tried using {last_url_segment} from the Current Extension, but that also produced the tag without the plus sign.

Does anyone have any ideas on how I can get the active class added?


Indeed {segment_x} would replace + with a space when parsed in templates, so {segment_3} and {websafe_tag} wouldn't match. Here are a few possible solutions:

  • Instead of {websafe_tag}, why not use {tag}? control+system+failure would be control system failure, which should match the {segment_3} which has spaces instead of + in templates.
  • You could always use tag_ids in your URL instead of websafe_tag. You can't go wrong with IDs, since they don't vary like words do.
  • You could use PHP to replace spaces with + in {segment_3} (or replace + with spaces in {websafe_tag}. Try turning on PHP and set it to Input and try this: {if "<?php echo str_replace(' ', '+', '{segment_3}'); ?>" == websafe_tag}. {segment_3} should parse before PHP kicks in, and therefore be available to the str_replace() PHP function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.