Reputation: 19482
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.
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.
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?
Upvotes: 1
Views: 10074
Reputation: 31991
You need inclusion tag here. Just pass your range in context and render it as you like. It gives you flexible and modular structure.
Upvotes: 2
Reputation: 7235
Check out this template tag: Template range tag. You should be able to extend it to handle characters as well.
Upvotes: 3