Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Useful django template tags and filters
# coding: utf-8
import json
from django import template
from django.utils.dateparse import parse_datetime
from django.utils.html import mark_safe
register = template.Library()
@register.filter
def get_range(value, start_from=0):
"""
Filter - returns a list containing range made from given value
Usage (in template):
<ul>{% for i in 3|get_range %}
<li>{{ i }}. Do something</li>
{% endfor %}</ul>
Results with the HTML:
<ul>
<li>0. Do something</li>
<li>1. Do something</li>
<li>2. Do something</li>
</ul>
Instead of 3 one may use the variable set in the views
"""
return range(start_from, value)
@register.filter('parse_datetime')
def parse_datetime_filter(date_string):
"""
Return a datetime corresponding to date_string, parsed according to DATETIME_INPUT_FORMATS
For example, to re-display a date string in another format::
{{ "01/01/1970"|parse_datetime|date:"F jS, Y" }}
"""
try:
return parse_datetime(date_string)
except Exception:
return date_string
@register.filter
def toJSON(value):
return mark_safe(json.dumps(value))
@register.filter
def addcss(field, arg):
"""
Add class to field in templates
{{ field|addcss:'my-class' }}
"""
return field.as_widget(attrs={'class': arg})
import os
import re
from django import template
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
__all__ = (
'js',
'css',
)
register = template.Library()
def _get_minified_file_path(path):
"""
Returns minified version file path of the given path
if exist else return given path
"""
file_dir, basename = os.path.split(path)
filename, ext = os.path.splitext(basename)
minified_file_path = os.path.join(
file_dir,
"{}.min{}".format(filename, ext)
)
if finders.find(minified_file_path):
return minified_file_path
return path
def _get_versioned_file_path(path):
"""
Versioning with query parameter prevent caching
So versioning with mtime of file
Serve same file with web server rewrite rule
Example nginx rewrite rule:
```
location ~* \.[0-9]+\.(css|js)$ {
rewrite (.*?)\.[0-9]+\.(css|js)$ $1.$2 last;
access_log off;
expires 365d;
}
```
"""
file_path_regex = re.compile(r"^(.*)\.(.*?)$")
mtime = int(os.path.getmtime(finders.find(path)))
# If path: /css/main.css
# Return same as: /css/main.1121221.css
return file_path_regex.sub(r"\1.{}.\2".format(mtime), path)
@register.simple_tag
def js(path, **kwargs):
"""
A simple shortcut to render a ``script`` html tag.
Example usage: {% js 'js/main.js' %}
"""
versioning = kwargs.get('versioning', True)
if settings.ASSET_VERSIONING:
path = _get_minified_file_path(path)
if versioning:
path = _get_versioned_file_path(path)
result = '<script type="text/javascript" src="{}"></script>'.format(
staticfiles_storage.url(path)
)
return mark_safe(result)
@register.simple_tag()
def css(path, **kwargs):
"""
Render a ``link`` tag to a static CSS file
Example usage: {% css 'css/style.css' %}
"""
versioning = kwargs.get('versioning', True)
if settings.ASSET_VERSIONING:
path = _get_minified_file_path(path)
if versioning:
path = _get_versioned_file_path(path)
result = '<link rel="stylesheet" href="{}" />'.format(
staticfiles_storage.url(path)
)
return mark_safe(result)
# Nginx rewrite rule for versioning static files.
....
location ~* \.[0-9]+\.(css|js)$ {
rewrite (.*?)\.[0-9]+\.(css|js)$ $1.$2 last;
access_log off;
expires 365d;
}
....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment