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 , .