Python Flask - Render Dict From Python to Jinja2 template

May 12, 2018 Oclemy Python Flask 8 minutes, 7 seconds

In this class we see how to pass a python dictionary from the backedn code to the frontend, basically from our Flask code to jinja2 template.

We then render the data from that dictionary to Materializecss list of Cards.

The cards have action buttons that when clicked show the currently selected item and description.

Let's go.

What is Flask?

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. Flask was created in 2010 by Armin Ronacher and is released under BSD license.

Flask is based on Werkzeug and Jinja2. Werkzeug enables Flask listen to and answer requests.

Jinja2 is a templating language and allows us pass data to our HTML user interface and perform basic expressions.

Here's a Hello World application:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World Camposha!'

if __name__ == '__main__':
    app.run()

We are building a Community in our YouTube Channel

We have a YouTube Channel that is growing very fast. This is because we provide quality tutorials consistently. Moreover we attempt to answer questions from YouTube comments as opposed to through this site.

Here's this tutorial in vide format:

Flask Installation

Flask can be installed via the following command:

pip install flask

For more details check here.

FlaskList.py

First we'll need to import Flask and render_template from flask module.

from flask import Flask,render_template

Then we'll instantiate Flask and hold it in an app variable.

app = Flask(__name__)

Then we'll define an index function and route it to the root url:

@app.route('/')
def index():

Our index function is basically going to render our jinja2 template, passing in simple strings as well as dict as well. The passed dict will then have its keys and values being rendered in a materializecss list of cards.

    return render_template('index.html',header='Amazing Universe', sub_header='Our universe is quite amazing', list_header="Galaxies!",

We'll define a function that actually returns the dict that will be rendered:

def get_galaxies():
    dict = {'Messier81': 'Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth'.....}
    return dict

Lastly we'll run the app in debug mode:

if __name__ == '__main__':
    app.run(debug=True)

Here's the full source code:

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',header='Amazing Universe', sub_header='Our universe is quite amazing', list_header="Galaxies!",
                       galaxies=get_galaxies(), site_title="Camposha.info")

def get_galaxies():
    dict = {'Messier81': 'Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth',
            'StarBurst': 'A starburst galaxy is a galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average..',
            'Cosmos Redshift':'Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter galaxy, in the constellation Sextans, about 12.9 billion light...',
            'Pinwheel': 'The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa ..',
            'Sombrero': 'Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo located 31 million light-years from Earth',
            'Whirlpool':'The Whirlpool Galaxy, also known as Messier 51a, M51a, and NGC 5194, is an interacting grand-design spiral galaxy ',
            'Andromeda':'The Andromeda Galaxy, also known as Messier 31, M31, or NGC 224, is a spiral galaxy approximately 780 kiloparsecs from',
            'Triangulum':'The Triangulum Galaxy is a spiral galaxy approximately 3 million light-years from Earth in the constellation Triangulum',
            'Canis Majos':'The Canis Major Dwarf Galaxy or Canis Major Overdensity is a disputed dwarf irregular galaxy in the Local Group',
            'Milky Way':'The Milky Way is the galaxy that contains our Solar System. The descriptive milky is derived from the appearance '

            }
    return dict

if __name__ == '__main__':
    app.run(debug=True)

index.html

This is our view. It is our jinja2 template in that it comprises both html markup and python expressions.

For example here's how we will be rendering the site title which will be passed from our python code:

    <title>{{ site_title }}</title>

Take note of the double curly braces, it denotes start of simple python expression.

We will also reference our static files like css from their directory with the help of jinja2 expression. We will then invoke the url_for() function passing in the directory name as well as the path:

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="{{ url_for('static',filename='css/materialize.min.css') }}" type="text/css" rel="stylesheet"
          media="screen,projection"/>
    <link href="{{ url_for('static',filename='css/style.css') }}" type="text/css" rel="stylesheet"
          media="screen,projection"/>

The header and subheader will also be passed from our python backend code and rendered via our jinja2 expressions:

    <h1 class="header center orange-text">{{ header }}</h1>
    <h4 class="center light-blue-text">{{ sub_header }}</h4>

A dict or dictionary is also passed to us from the python code and we need to render it in our jinja2 template. So we will create a for loop that will loop through the dict and print out the values in the our html.

We are able to get the keys and values from that dict, we will show both in a CardView. Ultimately we are displaying a list of cards.

            <!--LOOP THROUGH DICTIONARY-->
        {% for galaxy,description in galaxies.items() %}
        <li>
            <div class="card blue-grey darken-1">
                <div class="card-content white-text">
                    <span class="card-title">{{galaxy}}</span>
                    {{description}}
                </div>
                <div class="card-action">
                    <a onclick="alert('{{galaxy}}');">Show</a>
                    <a onclick="alert('{{description}}');">View</a>
                </div>

            </div>
        </li>
        {% endfor %}

You can also see that we will be handling onClick from javascript code. When the view button is clicked we show the dict value, in this case description.

On the other hand when the show button is clicked we display the dict key in our alert dialog.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ site_title }}</title>

    <!-- CSS  -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="{{ url_for('static',filename='css/materialize.min.css') }}" type="text/css" rel="stylesheet"
          media="screen,projection"/>
    <link href="{{ url_for('static',filename='css/style.css') }}" type="text/css" rel="stylesheet"
          media="screen,projection"/>

</head>

<body>
<!--NAVIGATION BAR-->
<nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container"><a id="logo-container" href="" class="brand-logo">{{ site_title }}</a>
        <ul class="right hide-on-med-and-down">
            <li><a href="">Home</a></li>
            <li><a href="">About</a></li>
        </ul>
        <a href="" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
    </div>
</nav>

<!--CONTAINER-->
<div class="container">
    <h1 class="header center orange-text">{{ header }}</h1>
    <h4 class="center light-blue-text">{{ sub_header }}</h4>

    <p>Here are our galaxies</p>
    <div class="row">
        <ul>
            <!--LOOP THROUGH DICTIONARY-->
        {% for galaxy,description in galaxies.items() %}
        <li>
            <div class="card blue-grey darken-1">
                <div class="card-content white-text">
                    <span class="card-title">{{galaxy}}</span>
                    {{description}}
                </div>
                <div class="card-action">
                    <a onclick="alert('{{galaxy}}');">Show</a>
                    <a onclick="alert('{{description}}');">View</a>
                </div>

            </div>
        </li>
        {% endfor %}
    </ul>
    </div>
</div>

<br>
<br>
<br>
<br>
<br>

<!--FOOTER-->
<footer class="page-footer orange">
    <div class="container">
        <div class="row">
            <div class="col l6 s12">
                <h5 class="white-text">Company Bio</h5>

                <p class="grey-text text-lighten-4">We are a team of college students working on this project like it's
                    our full time job.</p>
            </div>
            <div class="col l3 s12">
                <h5 class="white-text">Languages</h5>
                <ul>
                    <li><a class="white-text" href="#!">Javascript</a></li>
                    <li><a class="white-text" href="#!">PHP</a></li>
                    <li><a class="white-text" href="#!">Java</a></li>
                    <li><a class="white-text" href="#!">C#</a></li>
                </ul>
            </div>
            <div class="col l3 s12">
                <h5 class="white-text">Connect</h5>
                <ul>
                    <li><a class="white-text" href="#!">Facebook</a></li>
                    <li><a class="white-text" href="#!">Twitter</a></li>
                    <li><a class="white-text" href="#!">Google Plus</a></li>
                    <li><a class="white-text" href="#!">LinkedIn</a></li>
                </ul>
            </div>
        </div>
    </div>
</footer>

</body>
</html>

Result

Flask Pass Dictionary to View via Jinja2

Comments