本站首页    管理页面    写新日志    退出


«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7583423
建立时间:2006年5月29日




[Django]pycall Tag
软件技术

lhwork 发表于 2007/1/31 18:09:30

Code ¶from django import template from django.utils.translation import gettext_lazy as _ import re register = template.Library() r_identifers = re.compile(r'[\w.]+') class PyCallNode(template.Node): def __init__(self, expr_string, var_name): self.expr_string = expr_string self.var_name = var_name def __repr__(self): return "<PyCall node>" def render(self, context): clist = list(context) clist.reverse() d = {} d['_'] = _ for c in clist: d.update(c) m = r_identifers.match(self.expr_string) if m: module, func = m.group().rsplit('.', 1) funcstring = self.expr_string[len(module) + 1:] mod = __import__(module, {}, {}, ['']) d[func] = getattr(mod, func) else: raise template.TemplateSyntaxError, "The arguments of %r tag should be module.function(...)" % 'pycall' if self.var_name: context[self.var_name] = eval(funcstring, d) return '' else: return str(eval(funcstring, d)) def do_pycall(parser, token): try: tag_name, arg = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents[0] m = re.search(r'(.*?)\s+as\s+(\w+)', arg) if m: expr_string, var_name = m.groups() else: if not arg: raise template.TemplateSyntaxError, "The arguments of %r tag should be module.function(...)" % tag_name expr_string, var_name = arg, None return PyCallNode(expr_string, var_name) do_pycall = register.tag("pycall", do_pycall) How to use it ¶{% pycall os.path.abspath(".") %} {% pycall os.path.abspath(".") as path %} This is the {{ path }}. Syntax ¶{% pycall module.function(...) [as variable_name] %} If there is no as variable_name, the result will be output directly.


阅读全文(3656) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.047 second(s), page refreshed 144751803 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号