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

2014-09-03 12:31:40 +08:00
 hustlzp

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

2877 次点击
所在节点    Python
1 条回复
ericls
2014-09-03 12:39:25 +08:00
重载render_template,然后在其中将模板名赋予g,然后在模板中通过g获取模板名.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/131473

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX