Copy Highlighter-hljs
| |
| from django import template |
| |
| register = template.Library() |
| |
| |
| @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: |
| |
| 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: |
| 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 |
| |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步