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# Imports
3from django import template
4from django.conf import settings
5from django.forms.utils import flatatt
6from hashlib import md5
7from superdjango.html.shortcuts import parse_template
8from superdjango.html.utils import get_field_template, get_field_type, get_input_type, is_required_field, HTMLFramework
10register = template.Library()
12# Exports
14__all__ = (
15 "attr_of",
16 "field_type",
17 "flatten",
18 "gravatar",
19 "index_of",
20 "input_type",
21 "is_required",
22 "nlbr",
23 "replace",
24 "url_query_string",
25)
27# Tags
30@register.filter
31def attr_of(instance, name):
32 """Get the value of an attribute from a given instance.
34 :param instance: The instance.
36 :param name: The attribute name.
37 :type name: str
39 """
40 if type(instance) is dict:
41 try:
42 return instance[name]
43 except KeyError:
44 return None
46 return getattr(instance, name, None)
49@register.filter
50def field_template(instance):
51 """Get the template for a given field instance."""
52 return get_field_template(instance)
55@register.filter
56def field_type(instance):
57 """Get the type of field for the given field instance."""
58 return get_field_type(instance)
61@register.filter
62def flatten(attributes):
63 """An alias for Django's ``flatatt`` because I can never remember that name for some reason. Although, I probably
64 will now since I've created an alias for it.
65 """
66 return flatatt(attributes)
69@register.simple_tag
70def gravatar(user, size=60):
71 """Get the Gravatar for the given user."""
72 encoded_email = user.email.strip().lower().encode("utf-8")
73 email_hash = md5(encoded_email).hexdigest()
75 return "https://secure.gravatar.com/avatar/%s.jpg?s=%s" % (email_hash, size)
78@register.simple_tag(takes_context=True)
79def html(context, path, **kwargs):
80 if not path.endswith(".html"):
81 path += ".html"
83 # Get the full path to the template.
84 if not path.startswith("html/"):
85 path = "html/" + path
87 # The context argument is a RequestContext which is *not* a dictionary, but a contains a list of dictionaries that
88 # is iterable. To pass the context, we need to process each dictionary.
89 _context = dict()
90 for d in context:
91 _context.update(d)
93 # Add keyword arguments passed to the tag. These are specific to the template being loaded.
94 _context.update(kwargs)
96 # Return the output of the template.
97 return parse_template(path, _context)
100@register.filter
101def index_of(obj, index):
102 """Get the value from the given index.
104 :param obj: A list or tuple.
105 :type obj: list | tuple
107 :param index: The index to return.
108 :type index: int
110 """
111 try:
112 return obj[index]
113 except IndexError:
114 if settings.DEBUG:
115 raise
118@register.filter
119def input_type(field):
120 """Get the type of field (in lower case)."""
121 return get_input_type(field).lower()
124@register.filter
125def is_required(field):
126 """Indicates whether a form field is required."""
127 return is_required_field(field)
130@register.filter
131def nlbr(text):
132 """Replace new lines with a br tag."""
133 return text.replace("\n", "<br/>")
136@register.filter
137def replace(text, from_string, to_string):
138 """Replace a string."""
139 return text.replace(from_string, to_string)
142@register.simple_tag(takes_context=True)
143def url_query_string(context, skip=None):
144 """Return the request query string."""
145 if "request" not in context:
146 return ""
148 request = context['request']
150 _skip = list()
151 if skip is not None:
152 for i in skip.split(","):
153 _skip.append(i.strip())
155 url = list()
156 for key, value in request.GET.items():
157 if key in _skip:
158 continue
160 url.append("%s=%s" % (key, value))
162 if len(url) == 0:
163 return ""
164 elif len(url) == 1:
165 return "&" + "".join(url)
166 else:
167 return "&" + "&".join(url)