Camposha
  • Home
  • Android
  • Buy Projects
  • My Account
    • Become a Member
    • Log In|Log Out
    • Free Projects
No Result
View All Result
Camposha
  • Home
  • Android
  • Buy Projects
  • My Account
    • Become a Member
    • Log In|Log Out
    • Free Projects
No Result
View All Result
Camposha
No Result
View All Result
ADVERTISEMENT
Home Python

Python Flask – Render Dict From Python to Jinja2 template

2 years ago
in Python
Reading Time: 6min read
42 1
A A
43
SHARES
4.3k
VIEWS
Share on FacebookShare on Twitter
ADVERTISEMENT

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:

1
2
3
4
5
6
7
8
9
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:

1
pip install flask

For more details check here.

FlaskList.py

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

1
from flask import Flask,render_template

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

1
app = Flask(__name__)

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

1
2
@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.

1
    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:

1
2
3
4
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:

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

Here’s the full source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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:

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

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

SimilarPosts

Flask wtForms – Create Registeration Form then HTTP POST and GET

Flask wtForms – Create Registeration Form then HTTP POST and GET

2 years ago
4k
Python Flask – Introduction and Installation

Python Flask – Introduction and Installation

2 years ago
4k

Python Flask – Render List From Python to Jinja2 template

2 years ago
4.6k

Flask – Convert a Python Dict to JSON

2 years ago
4.4k

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:

1
2
3
4
5
6
    <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:

1
2
3
    <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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
            <!--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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!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

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
Share17Tweet11Send
ADVERTISEMENT

Related Posts

Flask wtForms – Create Registeration Form then HTTP POST and GET
Python

Flask wtForms – Create Registeration Form then HTTP POST and GET

December 19, 2020
4k
Python Flask – Introduction and Installation
Python

Python Flask – Introduction and Installation

December 19, 2020
4k
Python

Python Flask – Render List From Python to Jinja2 template

December 19, 2020
4.6k
Python

Flask – Convert a Python Dict to JSON

December 19, 2020
4.4k
CherryPy

Cherrypy – Pass List From Python to HTML via Jinja2

December 19, 2020
4.1k
CherryPy – Introduction
CherryPy

CherryPy – Introduction

December 19, 2020
4k
ADVERTISEMENT

Get Free Projects

  • Home
  • Android
  • Buy Projects
  • My Account

© 2021 Camposha

No Result
View All Result
  • Account
  • Activate
  • Activity
  • Become a Teacher
  • Become a Teacher
  • Become a Teacher
  • Become instructor
  • Blog
  • Blog
  • Cancel Payment
  • Cancel Payment
  • Cart
  • Change Password
  • Change Password
  • Checkout
  • Checkout
  • Checkout
  • Contact
  • Contact
  • Contact Us
  • Content restricted
  • Course Checkout
  • Dashboard
  • Edit Profile
  • Edit Profile
  • FAQs
  • Forgot Password
  • Forgot Password
  • Guest
  • Guest
  • Home
  • Home
  • Home Light
  • Instructor Dashboard
  • Instructor Registration
  • IUMP – Account Page
  • IUMP – Default Redirect Page
  • IUMP – Login
  • IUMP – LogOut
  • IUMP – Register
  • IUMP – Reset Password
  • IUMP – TOS Page
  • IUMP – Visitor Inside User Page
  • List courses
  • List wish list
  • Login
  • Login
  • Maintenance
  • Members
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Plans
  • My Account
  • OnePage Documentation
  • Portfolio Grid
  • Portfolio Masonry
  • Portfolio Multigrid
  • Privacy Policy
  • Products
  • Profile
  • Profile
  • Profile
  • Projects
  • Register
  • Register
  • Register
  • Register
  • Sample Page
  • Shop
  • Sign in
  • Sign up
  • Student profile
  • Student Registration
  • Thank You
  • Thank You

© 2021 Camposha

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In