I’m trying to pass an array to my template with a simple tag.
I created my module under app/templatetags/pages_navigation.py and in my opinion the code should be alright:
from django import template
from pages.models import Page
register = template.Library()
@register.simple_tag(name='links')
def pages_navigation():
pages = Page.objects.all()
links = [['Events','/']]
for page in pages:
links.append([page.title, '/'+page.url])
return {'links':links}
In my template I try to access links like this:
<ul>
{% if links %}
{% for link in links %}
<a href="{{link.1}}"><li>{{link.0}}</li></a>
{% endfor %}
{% else %}
<li>no pages found</li>
{% endif%}
</ul>
However, somehow it seems like links is always empty.
When I tried the pages_navigation method in the python shell it worked fine..
Is it possible that you can’t return arrays from simple tag methods?
From the docs:
simple tagsare for printing a piece of information, not assigning some result to a variable (a list in your case)So, you would be better of using an inclusion tag:
and creating a
links.htmlfile in your template directory:and in your original template you can include this:
which will call the template tag, render it and insert it into your template