Im looking for advice on desinging a web page with an A - Z index.
Kind of like :
http://www.bls.gov/bls/topicsaz.htm I have a long list of objects, with a title, that I want do display alphabetically, easy!
But I want to put in the A-Z with anchors, do I do this in the template,
I would have to loop through all the objects in the template, storing the currentletter as a global. Then check if each objects starts with the current letter etc etc.
It's not nice, is there any easier way that I am missing.
Maybe I should do it in the python code?
Django Model Index was introduced in Django 1.11. what is Model. indexes: By default, indexes are created with an ascending order for each column. To define an index with a descending order for a column, add a hyphen before the field's name.
context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. It defaults to an empty list.
A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102} , when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template.
Looking through the django template tags I found a nice way of doing it {{ifchanged}}, its worth mentioning for future use.
My list of objects is passed to my template ordered alphabetically:
Objects.get.all().order_by('title')
Then in my template i do :
# loop through all objects
{% for obj in objs %}
#display the letter only when it changes
{% ifchanged obj.title.0 %}<h1>{{obj.title.0}}</h1>{% endifchanged%}
# display the object
<h2>obj.title</h2>
{% endfor %}
Its a very handy 1 line peice of code in the template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With