In this Flask lesson we are going to learn How to Create Templates in Flask, we can use html templates in our Flask application.
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 html files in your templates folder, iam going to create three html files, the first one is index.html , the second one is contact.html and the third one is about.html.
templates/index.html
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Hello Flask Application From Template</h1> </body> </html> |
templates/contact.html
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>contact</title> </head> <body> <h1>Our Contact From Template</h1> </body> </html> |
templates/about.html
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>About</title> </head> <body> <h1>About Page From Template</h1> </body> </html> |
After creating of the templates now you can render these templates using render_template() function in the specific views.
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 28 29 30 |
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') @app.route('/contact') def Contact(): return render_template('contact.html') @app.route('/about') def About(): return render_template('about.html') #run flask app if __name__ == "__main__": app.run(debug=True) |
Run your flask application and go to http://localhost:5000/, this is the result.