2

I'm outputting all tags that are in use and then allowing the user to click these build up a query string to filter and display the results. It's all working fine.

Except, I'm having difficulty understanding what can I use to set an 'active' class on all the selected tags that are being added to the query string.

Setting 1 tag as active is simple enough, but when multiple are selected, I'm not so sure.

The URL looks like this: domain.com/learning/resources?tags=Video+Maths

Setting tags via getParam:

{% set tags = craft.request.getParam('tags') %} 

Listing all tags in use like this:

{% set resourceTags = craft.entries.section('resources').limit(null) %} {% for tag in craft.tags.relatedTo(resourceTags) %} 

Outputting results like this:

{% craft.entries.section('resources').limit(craft.config.paginateLimit).search(tags) as entries %}` 
1
  • I'm still having trouble with this. Is tags and search the wrong way to go about this? Commented Mar 10, 2016 at 14:13

2 Answers 2

1

The easiest way to do this is to create an array of tag ids for tags that should be active.

I would use a comma to separate multiple tags in your query string since the browser interprets a plus sign as a space. For example, if your tags were "New Videos" and "Maths" the url would look like this:

domain.com/learning/resources?tags=New+Videos,Maths

First, get the "tags" query parameter and make an array splitting each tag at a comma:

{% set tagsQuery = craft.app.request.getParam('tags')|split(',') %} {# tagsQuery = ["New Videos","Maths"] #} 

Search your tag group for matching titles and return an array of ids. This assumes you have a tag group with the handle "tags":

{% set activeTags = tagsQuery ? craft.tags.group('tags').title(tagsQuery).ids() : null %} 

Then it's a simple matter of testing if the tag.id is in the activeTags array.

{% for tag in craft.tags.relatedTo(resourceTags) %} {{ tag.title }} {# Use a conditional #} {% if item.id in activeTags %}active{% endif %} {# or an output tag with a conditional #} {{ item.id in activeTags ? 'active' }} {% endfor %} 
1

Perhaps not the most elegant solution, but this works:

{% set queryTags = craft.request.getQuery('tags') %} {% for tag in craft.tags.relatedTo(resourceTags) %} <a href="{% if tags == "" %}/learning/resources?tags={{ tag.title|kebab }}{% else %}/learning/resources?tags={{ tags|replace(' ', '+') }}+{{ tag.title|kebab }}{% endif %}" class="btn btn-default{% if tag.title|kebab in queryTags %} disabled{% endif %}" >{{ tag.title }}</a> {% endfor %} 

Adding disabled rather than active.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.