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:

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.

  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:

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.

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.

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

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:

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

Here’s the complete source code for our Controller.

FlaskList.py

OurFlasList.py 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():
    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:

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

<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.

index.html

Our index.html code:

<!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.