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]) + '…'
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:
#