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 List From Python to Jinja2 template

2 years ago
in Python
Reading Time: 6min read
46 0
A A
46
SHARES
4.6k
VIEWS
Share on FacebookShare on Twitter
ADVERTISEMENT

 

In this tutorial we see how to render a python list of data from Python backend code to jinja2 template.

Our frontend is based on Jinja2 templating language and we can easily pass list of data to html from our python code.

We will be using materializecss to render nice cards containing data from our Python list.

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.

Flask is designed to be as small and thin as possible so the feature set has to be limited. This makes Flask more unopinionated such that it caters for a wide variety of developers.

For instance with Flask, you can write a simple but fully working and deployable web app in a single file. Name the frameworks you know that can do that?

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

If you prefer a video tutorial check here:

What is Jinja2 ?

Jinja2 is a modern templating language for Python and was influenced by Django’s templates.

It’s fast and secure as it provides an optional sandboxed template execution environment.

More information about jinja2 can be found here.

What is Materializecss?

Materializecss is a modern responsive front-end framework based on Material Design. It speeds up development and yet allows us create awesome material design user interface components. It has a rich set of pre-built components that we can use.

In this class we will be interesetd in using Cards and List. So we will be displaying a list of cards. Those Cards will be rendering data from our python list.

You can download materializecss here or include it from CDN(Content Delivery Network). The links are in that page.

Flask Installation

Flask can be installed via the following command.We can use pip package manager:

1
pip install flask

For more details check here.

Let’s go.

Python List

list is a python built-in list type that allows us to work with sequences of data. List literals are written within square brackets [ ]. Lists work similarly to strings — use the len() function and square brackets [ ]to access data, with the first element at index 0.

Here’s an example of a List.

1
2
3
4
  languages = ['Python', 'Java', 'C#']
  print colors[0]    ## Python
  print colors[2]    ## C#
  print len(languages)  ## 3

Flask Example with List

Let’s start.

First you’ll specify imports:

1
from flask import Flask,render_template

In this case we’ve imported Flask and render_template from flask package.

Then we instantiate the Flask holding it in the app variable.

1
app = Flask(__name__)

We then define our index function and route it to the root url using the @app.route() decorator.
This function will be rendering our template via the render_template function and we specify template name, some strings that we are passing to template and the get_galaxies() function that will be returning a list. We will pass that list to our jinja2 template.

1
2
3
4
@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")

We define the list that will be passed to our template:

1
2
3
4
def get_galaxies():
    galaxies = ["Messier 81", "StarBurst", "Black Eye", "Cosmos Redshift", "Sombrero", "Hoags Object", "Andromeda","Pinwheel","Cartwheel",
    "Mayall's Object","Milky Way","IC 1101","Messier 87","Ring Nebular", "Centarus A", "Whirlpool", "Canis Major Overdensity","Virgo Stellar Stream"]
    return galaxies

Then run the app:

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

Here’s the complete source code for our Controller.

FlaskList.py

OurFlasList.py code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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():
    galaxies = ["Messier 81", "StarBurst", "Black Eye", "Cosmos Redshift", "Sombrero", "Hoags Object", "Andromeda","Pinwheel","Cartwheel",
    "Mayall's Object","Milky Way","IC 1101","Messier 87","Ring Nebular", "Centarus A", "Whirlpool", "Canis Major Overdensity","Virgo Stellar Stream"]
    return galaxies
 
if __name__ == '__main__':
    app.run(debug=True)
 

Our View/User interface

Then we come to our View.

First we’ll specify the url for our materializecss which is a static file. We’ll use the url_for() function in our jinja2 expression:

1
2
    <link href="{{ url_for('static',filename='css/materialize.min.css') }}" type="text/css" rel="stylesheet"
          media="screen,projection"/>

We’ll write a jinja2 block that will loop through our list and populate our materialize list of cards:

1
2
3
4
5
6
7
<ul class="collection with-header">
        <li class="collection-header"><h4><b>{{ list_header }}</b></h4></li>
{#    loop through galaxies and render them in list#}
        {% for galaxy in galaxies %}
            <li class="collection-item"><a href="#">{{ galaxy }}</a></li>
        {% endfor %}
    </ul>

Here’s the complete source code for our view.

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 Dict From Python to Jinja2 template

2 years ago
4.3k

Flask – Convert a Python Dict to JSON

2 years ago
4.5k

index.html

Our index.html 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
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
<!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"/>
 
</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>Value from the list: <b>{{ galaxies[3] }}</b></p>
 
    <p>Here are our galaxies</p>
    <ul class="collection with-header">
        <li class="collection-header"><h4><b>{{ list_header }}</b></h4></li>
{#    loop through galaxies and render them in list#}
        {% for galaxy in galaxies %}
            <li class="collection-item"><a href="#">{{ galaxy }}</a></li>
        {% endfor %}
    </ul>
</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

Best Regards.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
Share18Tweet12Send
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 Dict From Python to Jinja2 template

December 19, 2020
4.3k
Python

Flask – Convert a Python Dict to JSON

December 19, 2020
4.5k
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