Flask Templates

What are templates?

Have you ever tried to build a website? Did you encounter the problem that keeps the style of the website consistent, did you have to write the same code several times? Have you ever tried to change the style of that website?

If your website contains only a few pages, it will take time to change your style, but it's feasible. However, if you have many pages (for example, the list of items you sell in your store), this activity becomes overwhelming.

Using the templates, you can establish a basic layout for your pages and mention which element will change. In this way, you can define your header once and keep it consistent on all the pages of your website, and if you need to change your header, you will have to update it in one place.

Example

The following flask script contains a display function, which is the message () associated with the URL '/'. Instead of returning a simple string as a message, it returns a message with the <h1> tag attached through HTML.

from
flask import *
 app = Flask(__name__)
 @app.route('/')  
 def message():  
  return "<html><body><h1>Hi, welcome to  our website</h1></body></html>"  
 if __name__ == '__main__':   
 app.run(debug = True) 

Output is shown as below.

Flask Templates

Displaying external HTML files

Flask makes it easy for us to represent the external HTML file instead of encoding the HTML in the display function. Here, we can take advantage of the jinja2 template engine on which the flask is based. Flask provides us with the render_template () function that can be used to represent the external HTML file that will be returned in response to the view function.

Example

To represent an HTML file from the display function, we first create an HTML file called message.html.

message.html.

<html>  
 <head>  
 <title>Message</title>  
 </head>  
 <body>   
 <h1>hi, welcome to our first website </h1>  
 </body>  
 </html> 

Now create another file name index.py

index.py

from flask import *  
 app = Flask(__name__)  
 @app.route('/')  
 def message():  
 return render_template('message.html')  
 if __name__ == '__main__':  
 app.run(debug = True)  

Let’s run the index.py file from the cmd.

Flask Templates2

 Note: Here, we need to create folder templates within the application directory and save the HTML templates referenced by the globe script in that directory.

In our case, the path to our script.py script file is C:\Users\Erik_Akash\Documents\flask_app\env\Scripts, while the path to the HTML template is C:\Users\Erik_Akash\Documents\flask_app\templates function templates.

Application directory

script.py

Models

message.html

Delimiters

The Jinga 2 model engine provides some delimiters that can be used in HTML so that it can represent data dynamically. The model system provides some HTML syntaxes that are placeholders for variables and expressions that are replaced by their actual values when the model is represented.

The jinga2 model engine provides the following delimiters to exit HTML.

  • {# ... #} for the comments that are not included in the template output
  • {{ ... }} for expressions to print to the template output
  • {% ... %} for statements
  • # ... ## for line statements

Example

Consider the following example where the variable part of the URL is shown in the HTML script using the {{ ... }} delimiter.

<html>  
 <head>  
 <title>Message</title>  
 </head>  
 <body>   
 <h1>hi, {{ name }}</h1>  
 </body>  
 </html>  

Home1.py

from
flask import *  
 app = Flask(__name__)  
 @app.route('/user/<uname>')  
 def message(uname):  
 return render_template('message1.html',name=uname)  
 if __name__ == '__main__':  
 app.run(debug = True)   

Output

Flask Templates3

Variable part of the URL  address http://localhost:5000/user/admin is shown in the HTML script using the {{name}} placeholder.

 

 

Embedding Python statements in HTML

Due to the fact that HTML is a markup language and is used only for design purposes, sometimes in web applications, it may be necessary to execute the instructions for general purpose calculations. To this end, Flask facilitates the {% ...%} delimiter that can be used to incorporate simple Python instructions into HTML.

Referring Static files in HTML

Static files, such as CSS or JavaScript files, improve the display of an HTML web page. A web server is configured to serve these files from the static folder in the package or next to the module. Static files are available in the application / static path.

Example

In the following example, the flask script returns the HTML file, which is message.html, which is drawn using the style.css style sheet. The globe template system finds the static CSS file in the static / css directory. Then style.css is saved in the specified path.

Index2.py

from flask import *  
 app = Flask(__name__)   
 @app.route('/')  
 def message():  
 return render_template('message.html')  
 if __name__ == '__main__':  
 app.run(debug = True)    

message.html

<html>  
 <head>  
 <title>Message</title>  
 </head>  
 <body>   
 <h1>hi, welcome to our first website </h1>  
 </body>  
 </html> 
 Style.css
 body {  
   background-color: powderblue;  
 }  
 h1 {   
   color: blue;  
 }  
 p {  
   color: red;  
 } 

Output

Flask Templates4