From Script | Spoken-Tutorial
Revision as of 00:51, 12 August 2019 by SiddharthaSarkar (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of script: Introduction to Flask Templates

Author: Siddhartha Sarkar

Keywords: Video tutorial, Python Flask, flask templates, render_ template, jinja2, variables in templates.

Visual Cue Narration
Slide 1: Introduction to Flask templates Welcome to the Spoken Tutorial on Introduction to Flask templates.
Slide 2: Learning Objectives In this tutorial, we will learn to*
Use templates in Flask.
  • Use variables inside templates.
  • Gain insight about the View part of MVC.

Slides 3: System Requirements
To record this tutorial, I’m  using
Ubuntu Linux 16.04 OS
  • Python 3.5.2
  • Atom text editor 1.22.1 and
  • Firefox Web Browser

However, you may use any other editor or browser of your choice.

Slide 5:

To follow this tutorial, you should have working knowledge of
Linux commands
  • Python programming language and
  • HTML syntax

If not, then please go through the corresponding tutorials on this website. 
Slide 6: MVC Architecture Let us begin with the concept of MVC architecture.

MVC paradigm separates a web app into three interlinked components.

  • Model
  • View and
  • Controller.

Slide 7: MVC Architecture
Model is used to represent the application data.
  • We will talk more about it once we introduce database related things.

Slide 8: MVC Architecture
View is the presentation layer of MVC.
  • The appearance of the app is taken care of by the View component.

Slide 9: MVC Architecture
Controller is responsible for directing the execution flow of the app.
  • Once the requests are sent to the server,
    • the controller code processes the request
    • and sends back the response.

Slide 11: MVC Architecture
The templates are part of the View part of MVC.
  • Loosely speaking, templates are HTML pages that can be inherited.
  • We need a template engine for handling templates.

Slide 6: Templates

So far we have simply returned HTML code from the view functions.

  • By using templates, one can return an HTML file from the view functions.

Slide 7: Templates

One HTML file can inherit HTML code from another file with the help of templates.
  • For example, a typical website has some logo, header, etc. common in all pages.

Slide 8: Templates

So one can write a base HTML file template. 
  • And other pages can inherit the same base HTML file template.

Open a Terminal window

Let us open the Terminal by pressing Ctrl, Alt and T keys simultaneously on the keyboard.
Type cd project_flask & Press Enter
Now go to the folder project underscore flask which we created earlier using cd command.

$ . flask_venv/bin/activate

And activate our virtualenv.

dot space flask_venv slash bin slash activate

And press Enter.

Only narration Here onwards, please remember to press the Enter key after typing each command.
$ atom
Let’s open the file which we created earlier in this series, in any text editor.
[Text Editor]

Highlight HTML part in my_form().
Observe that the my_form() function returns raw HTML.

Now we will demonstrate how we can avoid returning raw HTML code.

For that we have to create our HTML template files in a separate folder called templates.


mkdir templates [Enter]
Switch to the terminal. 

And let’s create a folder named templates.

Type mkdir <space> templates.

[Editor: sample_template.html] Type <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <h1>The firstname value is Spoken</h1> </body> </html>

Let us write a simple HTML code to print the first name in a new file sample_template.html 

Type the code as shown here.

Press Ctrl + S And save the file.
Only Narration Now let us render this HTML file via python flask app

For this demonstration, let us define a new route in our hello_flask file.

Switch to in the text editor. Switch to the file in the text editor.

def template_ex():

return render_template('sample_template.html')

In the file, before the last if condition, type the code as shown here.

Highlight: render_template('sample_template.html') Inside this route we have used the function render_template provided by Flask.

This function is used to render an HTML template file.

Here we pass sample_template.html as an argument to the render_template function.

So, Flask will look for the file sample_template dot html inside the templates folder.

[Text Editor] Add , render_template

from flask import Flask, request, render_template
In the 1st line, we will import the method render_template.
Press Ctrl + S keys And then save the file
[Terminal] Now switch to the terminal.
$ export
And type  export <space> FLASK_APP <equal to > hello underscore flask dot py
Type $ python3 -m flask run [Enter]
Now run the server.


And press Enter.
Then, open a web browser and in the address bar, type 

And press Enter.

[Firefox] Highlight the text. We got the output of the HTML page.

So we have rendered the HTML code without hardcoding it inside the python file.

Only narration Now switch to the file

We can pass the variables as a parameter to the render_template method.

Let us see how we can do this.
def template_ex():
fname = 'Tutorial'
return render_template('sample_template.html', firstname = fname)
Update the template_ex method as shown here.
[Text Editor] highlight fname = ‘Tutorial’ I have declared a variable called fname here and assigned the value Tutorial to it.
[Text Editor] Highlight

return render_template('sample_template.html', firstname = fname)

Then I have passed this variable fname to the render_template method.

Now the value of the variable fname can be accessed via the variable firstname in the HTML file.

Press Ctrl + S keys Let’s save the file.
[Text Editor]
In sample_template.html

Highlight Spoken
And switch to sample_template.html file.

Here, we have explicitly mentioned Spoken as  firstname.

We will use jinja to interact the HTML file with the python file.

Slide 9: Jinja *
Jinja is a powerful templating language.
  • It allows generating HTML on the fly based on the request.
  • It supports control structures such as if-statements and for-loops.
  • Most importantly, it enables inheritance of HTML code.

Modify the body as

The firstname value is Template:Firstname

(within double curly braces firstname)

Switch to sample_template.html file.

To access a variable in Jinja, we have to write it within double curly braces.

So replace the word Spoken with within-double curly braces, firstname.

Press Ctrl + S Save the file.

$ python3 -m flask run
And switch to the terminal.

Stop the running server and start the server once again, by typing this command.


And press Enter.

Highlight Tutorial.

Then switch to the browser and refresh the page.

Observe that, we get Tutorial

That means we have successfully passed the variable from python to HTML.

[Text Editor]

 def my_form():
    if request.method == 'POST':
        firstname = request.form.get('firstname')
        lastname = request.form.get('lastname')

    return render_template('form1.html', fname=firstname, lname=lastname)

    return render_template('form2.html')
Once again, switch to the file and update the form route as shown.

Press Ctrl + S Save this file.
Only narration Now we have to create two HTML files form1.html and form2.html.
Press Ctrl + C
Switch to the terminal and stop the server.

atom templates/form1.html templates/form2.html  [Enter]
Now open form1.html and form2.html in a text editor.

[Text Editor] Show  form1.html

<!DOCTYPE html><html><head>    <title>Hello</title></head><body>   

The firstname value is: Template:Fname


The lastname value is: Template:Lname


In form1.html, add the following piece of code.

This code will simply display the firstname and lastname.

Press Ctrl + S Save the file.
[Text Editor] Show form2.html

<!DOCTYPE html><html><head>    <title>Hello</title></head><body>    <form method="POST">    Firstname: <input type="text" name="firstname">
    Lastname: <input type="text" name="lastname">
    <input type="submit" value="Submit">

In form2.html, add the following piece of code.

This code will  display a form to receive firstname and lastname.

Press Ctrl + S Again, save the file.

Type python3 -m flask run
Switch to the terminal.

And run the server again.


And press Enter.
Then switch to the browser.

And in the address bar, replace template with form and press Enter.

Firstname : Spoken

Lastname: Tutorial [Submit]

Enter the first name as Spoken.

And last name as Tutorial.

Then click on the Submit button.

[Browser] Highlight the text on screen. We got the output as desired.

Press Ctrl + C

Type deactivate and press Enter

Switch back to the terminal.

Let’s stop the server.

And deactivate the virtual environment.

Only narration
This brings us to an end of this tutorial.

Let us summarise.
Slide 8: Summary
In this tutorial, we learnt about-
Templating in flask to write clean code.
  • Using variables in the jinja2 templating language.
  • The View part of MVC.

Slide: About Spoken Tutorial project
The video at the following link summarises the Spoken Tutorial project.

Please download and watch it.
Spoken Tutorial workshops
The Spoken Tutorial Project team conducts workshops and gives certificates.

For more details, please write to us.
Slide: Forum for specific questions: Please post your timed queries in this forum.
Slide: Acknowledgement
Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.

More information on this mission is available at this link.
This is Siddhartha Sarkar signing off. 

Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Pravin1389, SiddharthaSarkar