Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the base url with Flask / Jinja2?

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?

like image 432
Martin Thoma Avatar asked Jul 20 '17 07:07

Martin Thoma


People also ask

How do I find the current URL of a Flask template?

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.

How do you use a Jinja2 Flask?

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.

What is base HTML in Flask?

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.


1 Answers

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?

  1. 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.
  2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs
  3. URL building handles escaping of special characters and Unicode data transparently.
  4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
  5. If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you.
like image 157
Martijn Pieters Avatar answered Oct 11 '22 18:10

Martijn Pieters