2

I'd like to be able to fetch a list of tags from a blog section and then group them into ranges of letters.

I've used this code to fetch and group a list of tags by first letter:

{% set entries = craft.entries.section('news') %}

{% set allTags = craft.tags.relatedTo({
  sourceElement: entries
}).order('name').limit(null) %}

{% set allTagsGrouped = allTags|group('name | first') %}

But what I'd like to do is to have groups for ranges of first letters like A–E, F–J, etc.

The end goal is to create an index of all of the tags in use, but group them under ranged letter headers instead of individual letter headers.

How would I go about doing this?

Thanks!

1 Answer 1

6

You can do this with the twigPCRE filter. Once you have your allTags, group them like this:

{% set allTagsGrouped = allTags|group('name|first|upper|preg_replace("/[A-M]/", "A-M", 1)|preg_replace("/[N-Z]/", "N-Z", 1)') %}

This takes the tag name, gets the first character, converts it to uppercase (so 'a' and 'A' are grouped together), and then maps all characters in the range A-M to the string "A-M", and all characters in the range N-Z to the string "N-Z". So allTagsGrouped will have two keys: "A-M", and "N-Z" (assuming all tag names start with letters). Obviously you could use more ranges.

Ordering allTags by name appears to be a case insensitive sort, so allTagsGrouped should still be in the right order.

1
  • Got around to implementing this and it worked perfectly. Thanks! Dec 29, 2014 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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