为django写的一个source的tag
#coding=utf-8 from django importtemplate
register=template.Library()#register.tag('source', do_source) @register.tag(name="source")defdo_source(parser, token):"""source can direct insert method return string into html
{% source myapp mymethod %}
or
{% source myapp mymethod arg0 arg1 arg2 %}
or
{% source myapp mymethod arg0,arg1,arg2 %}""" try:#split_contents() knows not to split quoted strings. args =token.split_contents()exceptValueError:raise template.TemplateSyntaxError("%r tag requires at least two arguments" %token.contents.split()[0])if len(args) < 2:raise template.TemplateSyntaxError("%r tag requires at least two arguments" %token.contents.split()[0])
model_name= args[1]
method_name= args[2]
params=[]if len(args) >=3:
params+= args[3:]if len(params) == 1:if ',' inparams[0]:
params= ['%s' % arg for arg in params[0].split(",")]#try to import this method try:
models= __import__(model_name, fromlist =[method_name])
method=getattr(models, method_name)except:raise template.TemplateSyntaxError("Can't import %s[%s]" %(model_name, method_name))returnSourceNode(method, params)classSourceNode(template.Node):def __init__(self, method, params):
self.method=method
self.params=paramsdefrender(self, context):try:
value= self.method(context, (arg for arg inself.params))except:from django.conf importsettingsifsettings.DEBUG:importsys,traceback
str= '<p> [%s] [%s] </p>' %(self.method, self.params)
str+= '<p> [%s] </p>' % traceback.format_exception(*sys.exc_info())returnstrelse:returnstrreturn value