from django import template
register = template.Library()
#####################################################################
# filters
######################################################################
@register.filter
def extra(value,args):
""" Return value with replaced characters of args to 0
extra = name of filter
value = value of variable that filter was applied to
args = arguments passed with filter """
return value.replace(args,str(0))
# template
{% load "something" %}
{{ somevariable|extra:"0" }}
# convert all to string befor processing
from django.template.defaultfilters import stringfilter
@register.filter
@stringfilter
def lower(value):
return value.lower()
####################################################################
# simple_tag
####################################################################
@register.simple_tag
def do_current_time(word, word2):
var = word + word2
return var.lower()
# template
{% do_current_time "He Loves WORD" " Peace And LOVE" %}
######################################################################
# Tags
#####################################################################
from django import template
import datetime
@register.tag
def do_current_time(parser, token):
"""
parser = template parser object
token = raw contents of the tag ( 'current_time "%Y-%m-%d %I:%M %p"' )
split_contents() = separates on spaces while keeping quoted strings together
template.TemplateSyntaxError = helpful messages, for any syntax error.
"""
try:
tag_name, format_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag required" % token.contents.split()[0]
if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return CurrentTimeNode(format_string[1:-1])
class CurrentTimeNode(template.Node):
def __init__(self, format_string):
self.format_string = format_string
def render(self, context):
return datetime.datetime.now().strftime(self.format_string)
##############################################################################
# inclustion_tag
##############################################################################
@register.inclusion_tag('left_menu.html')
def left_menu():
left_menu = Menu.objects.filter(side='left',page__name='news')
return {'left_menu':left_menu}
# with context
@register.inclusion_tag('link.html', takes_context=True)
def jump_link(context):
return {
'link': context['home_link'],
'title': context['home_title'],
'user': context['user'],
}
@register.inclusion_tag('profile.html', takes_context=True)
def some_tag(context, table):
return {
'table': table.objects.all()
'user': context['user'],
}
# template
1 {% left_menu %}
2 {% jump_link %}
3 {% some_tag Profile %}
Custom Tags