django를 위한 소스 태그

6573 단어 django
#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

좋은 웹페이지 즐겨찾기