- Author:
- mathwizard
- Posted:
- September 17, 2008
- Language:
- Python
- Version:
- 1.0
- Score:
- 2 (after 2 ratings)
Some frequently used filters and global functions:
url - same as django url tag
nbspize - replace all spaces with nbsp
get_lang - get current language code
timesince - converted django timesince tag
timeuntil - converted django timeuntil tag
truncate - tag that truncates text call it with an str argument like '20c' or '5w', where the number provides the count and c stands for charachters and w stands for words
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | from django.template.defaulttags import URLNode
from django.conf import settings
from jinja2.filters import contextfilter
from django.utils import translation
def url(view_name, *args, **kwargs):
from django.core.urlresolvers import reverse, NoReverseMatch
try:
return reverse(view_name, args=args, kwargs=kwargs)
except NoReverseMatch:
try:
project_name = settings.SETTINGS_MODULE.split('.')[0]
return reverse(project_name + '.' + view_name,
args=args, kwargs=kwargs)
except NoReverseMatch:
return ''
def nbspize(text):
import re
return re.sub('\s',' ',text.strip())
def get_lang():
return translation.get_language()
def timesince(date):
from django.utils.timesince import timesince
return timesince(date)
def timeuntil(date):
from django.utils.timesince import timesince
from datetime import datetime
return timesince(datetime.now(),datetime(date.year, date.month, date.day))
def truncate(text,arg):
import re
from django.utils.encoding import force_unicode
text = force_unicode(text)
matches = re.match('(\d+)([cw]{1})',arg)
if not matches:
return text
count = int(matches.group(1))
type = matches.group(2)
if type == 'c':
if count > len(text):
return text
else:
return text[:count] + '…'
elif type == 'w':
arr = text.strip().split()
if count > len(arr):
return ' '.join(arr)
else:
return ' '.join(arr[:count]) + '…'
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Thanks. And you can also reuse some directly from django. For example you can register these methods in env.filters: django.template.defaultfilters.linebreaks, django.template.defaultfilters.linebreaksbr, django.template.defaultfilters.urlencode
And if you want url() to automatically encode all parameters (not sure if the django tags does this, but I wanted it for my jinja filter), rename "def url" to "def url_noencode" and add:
#
Please login first before commenting.