I have a base.html
template which I would like to use for all pages. This base.html
contains a navigation
<nav>
<li><a href="./home">Home</a></li>
<li><a href="./foo">bar</a></li>
</nav>
This is no problem when I'm on the same level (e.g. localhost:5000/whatever
), but when I'm in a subfolder (e.g. localhost:5000/whatever/insert
) the links break.
This can be fixed by making the relative links absolute, e.g.
<nav>
<li><a href="{{base_url}}/home">Home</a></li>
<li><a href="{{base_url}}/foo">bar</a></li>
</nav>
However, I don't know how to get the base_url
. If possible, I would like to avoid adding base_url
to each render_template
call. And, if possible, I would also like to avoid to set base_url
manually.
How is this problem solved with Flask / Jinja2?
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.
Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present.
In Flask just like in most web development frameworks, you can make use of base templates and the extending of templates to reduce repetitive markup. In other words, you can have a base HTML file and have components from that shown on every single webpage.
Don't worry about a base url; if home
and foo
are routes in your Flask app, use the url_for()
function to build your URLs instead:
<nav>
<li><a href="{{ url_for('home') }}">Home</a></li>
<li><a href="{{ url_for('foo') }}">bar</a></li>
</nav>
Also see the URL Building section of the Flask Quickstart documentation:
Why would you want to build URLs using the URL reversing function
url_for()
instead of hard-coding them into your templates?
- Reversing is often more descriptive than hard-coding the URLs. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.
- You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs
- URL building handles escaping of special characters and Unicode data transparently.
- The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
- If your application is placed outside the URL root, for example, in
/myapplication
instead of/
,url_for()
properly handles that for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With