为django写的一个source的tag

#coding=utf-8
from django import template

register = template.Library()

#register.tag('source', do_source)
@register.tag(name="source")
def do_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()
    except ValueError:
        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 ',' in params[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))

    return SourceNode(method, params)

class SourceNode(template.Node):
    def __init__(self, method, params):
        self.method  = method
        self.params  = params

    def render(self, context):
        try:
            value = self.method(context, (arg for arg in self.params))
        except:
            from django.conf import settings
            if settings.DEBUG:
                import sys,traceback
                str = '<p> [%s] [%s] </p>' % (self.method, self.params)
                str += '<p> [%s] </p>' % traceback.format_exception(*sys.exc_info())
                return str
            else:
                return str
        return value

posted @ 2013-04-10 16:10  日月王  阅读(195)  评论(0编辑  收藏  举报