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

Viewed 10760

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?

2 Answers

If you have elements like,meta, a navbar, etc in your base.html that you would like to display across all pages in your site. You can type this at the top of each new page.

{% extends "base.html" %}
{% block content %}
    <!-- write page specific html between here -->  
{% endblock %}

its important to place

{% block content %} 
{% endblock %}

within you base.html file.

Related