Problems with simple_tag array values in Django Template

前端 未结 2 1649
别跟我提以往
别跟我提以往 2021-01-07 15:01

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:

2条回答
  •  灰色年华
    2021-01-07 15:21

    From the docs:

    Many template tags take a number of arguments -- strings or template variables -- and return a page_navigation after doing some processing

    simple tags are 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:

    @register.inclusion_tag('links.html')
    def page_navigation(a, b, *args, **kwargs):
        pages = Page.objects.all()
        links = [['Events','/']]
        for page in pages:
            links.append([page.title, '/'+page.url])
        return {'links':links}
    

    and creating a links.html file in your template directory:

      {% if links %} {% for link in links %}
    • {{link.0}}
    • {% endfor %} {% else %}
    • no pages found
    • {% endif%}

    and in your original template you can include this:

    {% load pages_navigation %}
    {% page_navigation %}
    

    which will call the template tag, render it and insert it into your template

提交回复
热议问题