Pass variables to other templates in Flask


Flask is one of my Python frame work in which I build simple web application with ease and peace. Today we learn how to pass a variables to other templates in a Flask application.

Suppose your web app have a base template and a top nav bar template which included using

{% include "site_template/top_navigation.html" %}

and you want to pass a title or something else from a Index page to navigation bar where you want show up some text.

Using {% set %} you can create global variables.

The solution

We can use a set block in top of the index page as follows ,to pass variables to other sub templates

{% set mytitle=title %}

In the route it will look like

return render_template('index.html',  title=title)

and in the nav bar page we can use as mytitle as variable using

<div id="site_title"><h2  >{{ mytitle}} </h2></div>

If you had doubt and suggestion please leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.