1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from functools import wraps
5 from django import template
6 from catalogue.models import Book
9 register = template.Library()
12 class StatsNode(template.Node):
13 def __init__(self, value, varname=None):
15 self.varname = varname
17 def render(self, context):
19 context[self.varname] = self.value
22 return str(self.value)
25 def register_counter(f):
26 """Turns a simple counting function into a registered counter tag.
28 You can run a counter tag as a simple {% tag_name %} tag, or
29 as {% tag_name var_name %} to store the result in a variable.
33 def wrapped(parser, token):
35 tag_name, args = token.contents.split(None, 1)
38 return StatsNode(f(), args)
40 return register.tag(wrapped)
44 def count_books_all():
45 return Book.objects.all().count()
50 return Book.objects.filter(children=None).count()
54 def count_books_parent():
55 return Book.objects.exclude(children=None).count()
59 def count_books_root():
60 return Book.objects.filter(parent=None).count()