This is our second tutorial in Python Flask, in this tutorial we are going to have Introduction to Flask Templates, so for this Flask looks for the templates folder inside the application folder.
If you are interested in Web Development with Django Framework, than you can read
the complete articles with video training in this link, Django Web Development Tutorials.
Also in the previous tutorial we had a complete introduction to Flask Web Framework,
you can check this link Flask Introduction & Installation.
The first step is that create a new folder at name of templates, make sure that it has the
same spelling, if you don’t do this, you will not see the content of your template.
After that you need to create an html file in your templates folder, iam going to create two html files, the first one is index.html and the second one is contact.html.
OK now this is our app.py file, and we have rendered our templates in our view functions.
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 |
from flask import Flask, render_template #create the object of Flask app = Flask(__name__) #creating our routes @app.route('/') def index(): return render_template('index.html') #contact routes @app.route('/contact') def Contact(): return render_template('contact.html') #run flask app if __name__ == "__main__": app.run(debug=True) |
The function render_template provided by Flask integrates the Jinja2 template engine with the application.
This function takes the filename of the template as its first argument.
Any additional arguments are key/value pairs that represent actual values for variables referenced in the template.
OK now let’s create our html files.
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Home Page - Welcome to codeloop.org</h1> <h3>Tutorial Nimber 2 </h3> <p> In this tutorial we are going to talk about templates </p> </body> </html> |
templates/contact.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Contact</title> </head> <body> <h1>Contact Page - Welcome to codeloop.org</h1> <h3>Tutorial Nimber 2 </h3> <p> In this tutorial we are going to talk about templates </p> </body> </html> |
If you run your project this will be the result
http://localhost:5000/
http://localhost:5000/contact
Also you can watch my complete 4 hours training on Flask Web Development
Subscribe and Get Free Video Courses & Articles in your Email
Comments are closed.