如何在jinja2/flask中获取当前URL(request.URL不工作)

2024-09-17 18:09:45 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在Jinja2/Flask中打印当前的URL?

例如,如果当前URL是http://www.domain.com/example/1/2

{{ request.path }}可以工作并打印/example/1/2,但是如何使用http://获得完整的URL呢?

从文档中(here){{ request.url }}应该可以工作,但它不会产生任何结果。

谢谢

更新

以下是views.py中的render/context参数:

class EventDetailView(EventObjectMixin, FormView):
    template_name = 'gig/public/about.html'
    context_object_name = 'event'
    form_class = EventPurchaseTicketForm

    def get_context_data(self, **kwargs):
        context = super(EventDetailView, self).get_context_data(**kwargs)

    ...

        return context

Tags: nameselfhttpurljinja2flaskdataget
3条回答

你可以使用{{ url_for(request.endpoint) }},它可以工作。

查找与此类似的代码,通常在controller.pyinit\uuuu.pyviews.py中找到:

from flask import render_template
...

@app.route('/example/<arg1>/<arg2>')
def some_view_function(arg1, arg2):
    ...

    return render_template('path/to/your/template.html')

render_template()一起使用的是请求和其他变量。

flask.request对象提供了获取URL的不同方法。有关信息,请参见the documentation

相关问题 更多 >