V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hustlzp
V2EX  ›  Python

如何在 Jinja2 模板中,获取当前模板的 name?

  •  1
     
  •   hustlzp ·
    hustlzp · 2014-09-03 12:31:40 +08:00 · 2836 次点击
    这是一个创建于 3532 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如 return render_template('site/index.html') 之后,模板中可以获取'site/index.html'这个值。

    在StackOverflow中找到了一个很tricky的方法:

    http://stackoverflow.com/a/12302893

    If all you need is the basename, you can use {{ self }} which will return a repr string containing the basename of the template, e.g., <TemplateReference 'view.html'>. You could parse this with a filter, e.g., {{ self | quoted }}

    @app.template_filter('quoted')
    def quoted(s):
        l = re.findall('\'([^\']*)\'', str(s))
        if l:
            return l[0]
        return None
    

    有没有更好的方法呢?

    重载render_template?然后在其中将模板名赋予g,然后在模板中通过g获取模板名?

    第 1 条附言  ·  2014-09-03 13:29:49 +08:00
    self._TemplateReference__context.name
    1 条回复    2014-09-03 12:39:25 +08:00
    ericls
        1
    ericls  
       2014-09-03 12:39:25 +08:00
    重载render_template,然后在其中将模板名赋予g,然后在模板中通过g获取模板名.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   863 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 18:54 · PVG 02:54 · LAX 11:54 · JFK 14:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.