# Imports
from django import template
from django.conf import settings
from django.forms.utils import flatatt
from hashlib import md5
from superdjango.html.shortcuts import parse_template
from superdjango.html.utils import get_field_template, get_field_type, get_input_type, is_required_field, HTMLFramework
register = template.Library()
# Exports
__all__ = (
"attr_of",
"field_template",
"field_type",
"flatten",
"gravatar",
"html",
"index_of",
"input_type",
"is_required",
"nlbr",
"replace",
"url_query_string",
)
# Tags
[docs]@register.filter
def attr_of(instance, name):
"""Get the value of an attribute from a given instance.
:param instance: The instance.
:param name: The attribute name.
:type name: str
"""
if type(instance) is dict:
try:
return instance[name]
except KeyError:
return None
return getattr(instance, name, None)
[docs]@register.filter
def field_template(instance):
"""Get the template for a given field instance."""
return get_field_template(instance)
[docs]@register.filter
def field_type(instance):
"""Get the type of field for the given field instance."""
return get_field_type(instance)
[docs]@register.filter
def flatten(attributes):
"""An alias for Django's ``flatatt`` because I can never remember that name for some reason. Although, I probably
will now since I've created an alias for it.
"""
return flatatt(attributes)
[docs]@register.simple_tag
def gravatar(user, size=60):
"""Get the Gravatar for the given user."""
encoded_email = user.email.strip().lower().encode("utf-8")
email_hash = md5(encoded_email).hexdigest()
return "https://secure.gravatar.com/avatar/%s.jpg?s=%s" % (email_hash, size)
[docs]@register.simple_tag(takes_context=True)
def html(context, path, **kwargs):
"""Get HTML for the given path."""
if not path.endswith(".html"):
path += ".html"
# Get the full path to the template.
if not path.startswith("html/"):
path = "html/" + path
# The context argument is a RequestContext which is *not* a dictionary, but a contains a list of dictionaries that
# is iterable. To pass the context, we need to process each dictionary.
_context = dict()
for d in context:
_context.update(d)
# Add keyword arguments passed to the tag. These are specific to the template being loaded.
_context.update(kwargs)
# Return the output of the template.
return parse_template(path, _context)
[docs]@register.filter
def index_of(obj, index):
"""Get the value from the given index.
:param obj: A list or tuple.
:type obj: list | tuple
:param index: The index to return.
:type index: int
"""
try:
return obj[index]
except IndexError:
if settings.DEBUG:
raise
[docs]@register.filter
def is_required(field):
"""Indicates whether a form field is required."""
return is_required_field(field)
[docs]@register.filter
def nlbr(text):
"""Replace new lines with a br tag."""
return text.replace("\n", "<br/>")
[docs]@register.filter
def replace(text, from_string, to_string):
"""Replace a string."""
return text.replace(from_string, to_string)
[docs]@register.simple_tag(takes_context=True)
def url_query_string(context, skip=None):
"""Return the request query string."""
if "request" not in context:
return ""
request = context['request']
_skip = list()
if skip is not None:
for i in skip.split(","):
_skip.append(i.strip())
url = list()
for key, value in request.GET.items():
if key in _skip:
continue
url.append("%s=%s" % (key, value))
if len(url) == 0:
return ""
elif len(url) == 1:
return "&" + "".join(url)
else:
return "&" + "&".join(url)