Difference between revisions of "Python-Flask/C2/Introduction-to-Flask-Templates/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
(One intermediate revision by one other user not shown)
Line 291: Line 291:
 
|| And switch to the '''terminal'''.
 
|| And switch to the '''terminal'''.
  
Stop the running '''server '''and '''start''' the '''server''' once again, by typing this '''command'''.
+
Stop the running '''server '''and '''start''' the '''server''' once again.
 
|-
 
|-
 
|| Type http://127.0.0.1:5000
 
|| Type http://127.0.0.1:5000
Line 300: Line 300:
 
|| Then switch to the '''browser''' and refresh the page.
 
|| Then switch to the '''browser''' and refresh the page.
  
Observe that, we get '''Tutorial'''.
+
Observe that we get '''Tutorial'''.
  
 
That means we have successfully passed the '''variable''' from '''python''' to '''HTML'''.
 
That means we have successfully passed the '''variable''' from '''python''' to '''HTML'''.
Line 328: Line 328:
  
 
Press Ctrl + C
 
Press Ctrl + C
|| Switch to the terminal and stop the '''server'''.
+
|| Switch to the '''terminal''' and stop the '''server'''.
 
|-
 
|-
 
|| [Terminal]
 
|| [Terminal]
Line 395: Line 395:
 
|-
 
|-
 
|| Press '''Ctrl + S'''
 
|| Press '''Ctrl + S'''
|| Again, save the file.
+
|| Save the file.
 
|-
 
|-
 
|| [Terminal]
 
|| [Terminal]
Line 410: Line 410:
 
|| Then switch to the '''browser'''.
 
|| Then switch to the '''browser'''.
  
And in the '''address bar''', replace '''template''' with '''form''' and press '''Enter'''.
+
In the '''address bar''', replace '''template''' with '''form''' and press '''Enter'''.
 
|-
 
|-
 
|| [Browser]
 
|| [Browser]
Line 438: Line 438:
 
|-
 
|-
 
|| Only narration
 
|| Only narration
|| This brings us to an end of this tutorial.
+
|| This brings us to the end of this tutorial.
  
 
Let us summarise.
 
Let us summarise.
Line 445: Line 445:
 
|| In this tutorial, we learnt about-
 
|| In this tutorial, we learnt about-
  
* '''Templating''' in '''flask''' to write clean code.
+
* '''Templating''' in '''Flask''' to write clean code.
 
* Using '''variables''' in the '''jinja2 templating language.'''
 
* Using '''variables''' in the '''jinja2 templating language.'''
 
* The '''View''' part of '''MVC'''.
 
* The '''View''' part of '''MVC'''.

Latest revision as of 17:27, 27 August 2019

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: Pre-requisites 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)
  • 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)
  • 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)
  • 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.
[Terminal]

Type cd project_flask & Press Enter

Now go to the folder project underscore flask which we created earlier using cd command.
[Terminal]

$ . flask_venv/bin/activate [Enter]

And activate our virtualenv.

Type 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.
[Terminal]

Type $ atom hello_flask.py

Let’s open the hello_flask.py file which we created earlier in this series, in any text editor.
[Text Editor] hello_flask.py

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.

[Terminal]

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 hello_flask.py in the text editor. Switch to the file hello_flask.py in the text editor.
[Editor: hello_flask.py]

@app.route('/template')

def template_ex():

return render_template('sample_template.html')

In the hello_flask.py 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.
[Terminal]

Type

$ export FLASK_APP=hello_flask.py

And type export <space> FLASK_APP <equal to > hello underscore flask dot py
[Terminal]

Type $ python3 -m flask run [Enter]

Now run the server.
[Firefox]

Type http://127.0.0.1:5000/template

And press Enter.

Then, open a web browser and in the address bar, type

http://127.0.0.1:5000/template

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

<h1>The firstname value is {{ firstname }}</h1>

(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.
[Terminal]

Type $ python3 -m flask run [Enter]

And switch to the terminal.

Stop the running server and start the server once again.

Type http://127.0.0.1:5000

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] hello_flask.py
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 hello_flask.py 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.
Terminal

Press Ctrl + C

Switch to the terminal and stop the server.
[Terminal]

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>

<h1>The firstname value is: {{ fname }}</h1>
<h1>The lastname value is: {{ lname }}</h1>

</body>

</html>

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"><br>

Lastname: <input type="text" name="lastname"><br>

<input type="submit" value="Submit"><br>

</form>

</body> </html>

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

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

Press Ctrl + S Save the file.
[Terminal]

Type python3 -m flask run

Switch to the terminal.

And run the server again.

[Browser]

Type http://127.0.0.1:5000/form

And press Enter.

Then switch to the browser.

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

[Browser]

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.
[Terminal]

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

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