In Django, how can I iterate over the result of a custom template tag that requires arguments?

If I created a template tag:

@register.simple_tag
def last_books(a_cat, cutoff=5):
    objects = Books.objects.filter(category=a_cat)
    return objects[:cutoff]

How can I do something like this in my template:

{% for book in last_books 'Sports' 3 %}

I am currently getting this error:

'for' must use the format "for x in y": for x in last_books "Sports" 3

+3
source share
2 answers

Personally, I would just pass the book as a context variable through the view. This way you do not need to use a template tag.

Alternatively, you can use the include_tag decorator instead, which completes the idea of ​​rendering the include template with a custom context in the current document.

, simple_tag . , string, . , , . , . node - :

class LastBooksNode(template.Node):
    def __init__(self, category, cutoff=5, var_name='books'):
        self.category = category
        self.cutoff = cutoff
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = Books.objects.filter(category=self.category)[:self.cutoff]
        return ''

@register.tag(name='last_books')
def do_last_books(parser, token):
    error = False
    try:
        tag_name, category, cutoff, _as, var_name = token.split_contents()
        if _as != 'as':
            error = True
    except:
        error = True

    if error:
        raise TemplateSyntaxError, 'last_books must be of the form, "last_books <category> <cutoff> as <var_name>"'
    else:
        return LastBooksNode(a_cat, cutoff, var_name)

:

{% import <your tag library> %}
{% last_books 'category' 5 as my_books %}
{% for book in my_books %}
    ....
{% endfor %}

, , . , include_tag , .

+7
+2

Source: https://habr.com/ru/post/1704839/


All Articles