How to get current URL in jinja2/flask (request.url not working)
Question:
Is there a way to print the current URL in Jinja2/Flask?
E.g. if the current URL is http://www.domain.com/example/1/2
{{ request.path }}
works and prints /example/1/2
, but how to I get the full URL with http:// as well?
From the docs (here){{ request.url }}
should work, but it doesn’t yield anything.
Thanks
UPDATE
Here are the render/context args from views.py:
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
Answers:
Find where you have similar code to this, usually found in controller.py or __ init__.py or views.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')
With render_template()
are request and other variables available to you.
You can use {{ url_for(request.endpoint) }}
, it works.
For folks who have routes that require additional arguments, the accepted answer won’t quite work, as mentioned by @lfurini.
The following will use the view’s arguments when constructing the URL:
{{ url_for(request.endpoint, **request.view_args) }}
Is there a way to print the current URL in Jinja2/Flask?
E.g. if the current URL is http://www.domain.com/example/1/2
{{ request.path }}
works and prints /example/1/2
, but how to I get the full URL with http:// as well?
From the docs (here){{ request.url }}
should work, but it doesn’t yield anything.
Thanks
UPDATE
Here are the render/context args from views.py:
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
Find where you have similar code to this, usually found in controller.py or __ init__.py or views.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')
With render_template()
are request and other variables available to you.
You can use {{ url_for(request.endpoint) }}
, it works.
For folks who have routes that require additional arguments, the accepted answer won’t quite work, as mentioned by @lfurini.
The following will use the view’s arguments when constructing the URL:
{{ url_for(request.endpoint, **request.view_args) }}