Coverage for superdjango/html/templatetags/lazy_loader.py : 0%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2The lazy loader is a replacement for the ``load`` template tag that allows template tags to be conditionally loaded and
3used. It is inspired by `django-friendly-tag-loader`_, but is intentionally much less robust.
5.. _django-friendly-tag-loader: https://github.com/ataylor32/django-friendly-tag-loader
7See also: https://stackoverflow.com/q/7835155/241720
9Generic templates and templates provided by contrib apps utilize lazy loader to conditionally load and snippet tags.
11"""
12from django.template.base import TokenType
13from django.template.defaulttags import find_library, CommentNode, IfNode, LoadNode
14from django.template.library import Library, TemplateSyntaxError
15from django.template.smartif import Literal
16import logging
18TOKEN_BLOCK = TokenType.BLOCK
20log = logging.getLogger(__name__)
21register = Library()
24@register.tag
25def lazy_load(parser, token):
26 """Load template tag library if it exists.
28 .. code-block::
30 {% load lazy_loader %}
31 {% lazy_load support_tags %}
33 """
34 library_name = token.split_contents()[-1]
36 try:
37 library = find_library(parser, library_name)
38 parser.add_library(library)
39 except TemplateSyntaxError as e:
40 log.debug("Lazy load failed: %s" % e)
41 pass
43 return LoadNode()
46@register.tag
47def if_tag_exists(parser, token):
48 """Determine if a given tag exists before calling it.
50 .. code-block::
52 {% if_tag_exists sidebar_items %}
53 {% sidebar_items page=page %}
54 {% else %}
55 No sidebar for you!
56 {% endif_tag_exists %}
58 """
59 bits = list(token.split_contents())
60 if len(bits) < 2:
61 raise TemplateSyntaxError("%r requires an argument." % bits[0])
63 end_tag = "end%s" % bits[0]
64 has_tag = all([tag in parser.tags for tag in bits[1:]])
65 nodelist_true = nodelist_false = CommentNode()
66 if has_tag:
67 nodelist_true = parser.parse(("else", end_tag))
68 token = parser.next_token()
69 if token.contents == "else":
70 parser.skip_past(end_tag)
71 else:
72 while parser.tokens:
73 token = parser.next_token()
74 if token.token_type == TOKEN_BLOCK and token.contents == end_tag:
75 return IfNode([
76 (Literal(has_tag), nodelist_true),
77 (None, nodelist_false)
78 ])
79 elif token.token_type == TOKEN_BLOCK and token.contents == "else":
80 break
81 else:
82 pass
84 nodelist_false = parser.parse((end_tag,))
85 parser.next_token()
87 return IfNode([
88 (Literal(has_tag), nodelist_true),
89 (None, nodelist_false)
90 ])