Search code examples
djangodjango-templatesdjango-viewsdjango-taggit

Django: How shouldI loop through Taggit tag's and list them alphabetically while at the same time seperating them in template?


I've seen this in a lot of sites actually, and I was wondering how I would go about replicating the functionality. Basically the tags follow this kind of pattern

A | all tags that start with A         Y | all tags that start with Y

B | all tags that start with B         Z | all tags that start with Z

A, B, ... Y, Z would probably be in something like an <h5> tag and all the tags in <li> tags

Essentially I want that tag list page to show all the tags used throughout the blog alphabeticalized.

I have an idea how to do it, but it may not be pretty practical. I was thinking about going through all the tags, grabbing the first letter of each item, putting it in a new dictionary and then looping through that dictionary to display in my templates.

Would that be a practical way to do it?

I also do have 3rd party apps taggit and https://github.com/fizista/django-taggit-templatetags2


Solution

  • This sounds like something views can handle better. Create a dictionary where key is an alphabet and value is array of related tags. pass it to context.

    Dict_you_want = {'A':['apple','argentina','aron'], 'B':['ball','banana'], ....,
                     . . . . . .. . . . . 
                     'Z':['zebra','zeon']}
    context['dict_you_want'] = Dict_you_want
    

    Once in html template you can loop over it and render it the way you want.