Intention
In my Django template, I create a link for each letter in the alphabet and each digit 1-9 to link to an index page.
In Python code, this is what it would look like:
for ch in map(chr, range(97, 123)) + range(1,10):
print '<a href="/indexpage/{0}/">{0}</a>'.format(ch)
But I want to do this in a Django template, so I can’t use the map/range functions directly.
Failed Attempts
At first, I thought about creating a template tag that returns the alphanumeric character list, and then looping over it in the template, but this does not work, as it’s a tag and not a context variable.
Templatetag:
@register.simple_tag
def alnumrange():
return map(chr, range(97, 123)) + range(1,10)
Template:
{% for ch in alnumrange %}
<a href="/indexpage/{{ch}}/">{{ch}}</a>
{% endfor %}
I thought it might work when using the with tag, but it didn’t either.
Further thoughts
- I can’t set the context in a view as this is a base template which I extend.
- I don’t want to add a context processor, as I use this range only in a single template.
Is there a way to turn the template tag output into a context variable over which I can iterate? Or is there another way I should solve this?
You need inclusion tag here. Just pass your range in context and render it as you like. It gives you flexible and modular structure.