V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Sep 3, 2014 · 3268 views
    This topic created in 4261 days ago, the information mentioned may be changed or developed.

    比如 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获取模板名?

    Supplement 1  ·  Sep 3, 2014
    self._TemplateReference__context.name
    1 replies    2014-09-03 12:39:25 +08:00
    ericls
        1
    ericls  
       Sep 3, 2014
    重载render_template,然后在其中将模板名赋予g,然后在模板中通过g获取模板名.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2318 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:52 · PVG 23:52 · LAX 08:52 · JFK 11:52
    ♥ Do have faith in what you're doing.