Building a website is a bit like cooking. You need to master a few key techniques “GET, POST, PUT, and DELETE” to handle your ingredients, or in this case, your data. ‘GET’ grabs the data, while the others change it up in various ways. But here’s the thing: just changing the data doesn’t update what your visitors see. That’s where HTML templates come in, acting like your presentation plates, showcasing your updates beautifully based on the changes you’ve made.
In today’s tutorial, we’re going to learn how to use these HTML templates to build our website, In other words, we will write the main code as well as the code for the HTML files that will be integrated into it.
Let’s get started!
Table of Contents
- Getting Started
- Necessary Libraries
- Imports
- Creating Flask App Instance
- Defining Routes
- Starting the Flask Server
- Full Code
- Conclusion
Getting Started
To set up your Flask project with HTML templates, you’ll need to create a directory named ‘templates‘ in your project folder. This ‘templates‘ directory will house the HTML files you create for your project.
Got PyCharm? Setting up a new directory is a breeze. Just give your project root a quick right-click in the project explorer, hit ‘New‘, then ‘Directory‘, and call it ‘templates‘. Once that’s done, populating it with HTML files is just as easy. Right-click on your shiny new ‘templates‘ folder, click ‘New‘ again, but this time go for ‘HTML File‘. Make sure to name it just like you did in your main code – this part’s super important because if the names don’t match up, things might not run as smoothly as you’d like.
You can also create it by simply going to the project file on your desktop you can manually create a new file and call it ‘templates‘, and within that, start making your HTML files. Just open a new text document, type up your HTML, and change the file’s extension from ‘.txt‘ to ‘.html‘. Simple and effective.
Necessary Libraries
Make sure to install the Flask library via the terminal or your command prompt for the code to function properly:
$ pip install flask
PS: An HTML template is a file that contains the basic structure and layout of a webpage. In other words, it dictates how the webpage appears to the user.
Imports
As usual, we begin by importing the Flask
class from the flask
module, allowing us to customize our Flask application later on. Then, we import the render_template
function, which is essential for integrating HTML templates into our project.
from flask import Flask, render_template
Creating Flask App Instance
This is the part where we start customizing our flask
class by creating an instance and making sure that Flask remembers its name down the road.
app = Flask(__name__)
Defining Routes
Route for the Home Page
When the user visits the generated URLs, our Flask application will call the index()
function, which will retrieve the results from the “index.html” template and display the homepage for the user. In other words, we will create a route to the homepage for the user.
Check this tutorial if you want to learn more about routes and requests.
@app.route('/')
def index():
return render_template('index.html')
Route for the About Page
Similar to the previous route, when the user visits the About page our Flask application will call the about()
function which will retrieve the results from the “about.html” template by using the render_template
function.
@app.route('/about')
def about():
return render_template('about.html')
Route for the Contact Page
Similar to the other routes, this one takes the user to the contact page when he visits the said page by the same steps, Flask will call the contact()
function which will retrieve the results from the “contact.html” template by using the render_template
function.
@app.route('/contact')
def contact():
return render_template('contact.html')
Starting the Flask Server
This part makes sure that this script can only be run directly and not imported as a module. As well as make the Flask development server accessible to all devices on the network on port 5000 and enable debugging.
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000,debug=True)
Full Code
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000,debug=True)
Index HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<div>
<h1>Welcome to our website</h1>
<p>This is the home page.</p>
<p>Feel free to explore!</p>
<p>Go to <a href="{{ url_for('about') }}">About</a> to learn more about us.</p>
<p>Go to <a href="{{ url_for('contact') }}">Contact</a> to know how to reach us.</p>
</div>
</body>
</html>
Document Type:
This part indicates that the document type is an HTML.
<!DOCTYPE html>
HTML Tag:
This part specifies the language of the HTML. In this case, it is English.
<html lang="en">
Head Section:
This part tells the browser which character encoding to use, as well as, the title of the Website and how its layout should be on Mobile phones or desktop computers.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
Body Section:
As the name suggests, this is the body of the HTML which contains the information that will be displayed on the browser, as you can see it starts with <div>
for division – there is a heading that says “Welcome to our Website” then there are paragraphs below <p>
where you write what you want to appear on the homepage, then there is the <a href
which are dynamic URLs when the user clicks them they take him to a different page.
<body>
<div>
<h1>Welcome to our website</h1>
<p>This is the home page.</p>
<p>Feel free to explore!</p>
<p>Go to <a href="{{ url_for('about') }}">About</a> to learn more about us.</p>
<p>Go to <a href="{{ url_for('contact') }}">Contact</a> to know how to reach us.</p>
</div>
</body>
</html>
Example 1
This is what this HTML shows:
About HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us</title>
</head>
<body>
<div>
<h1>About Us</h1>
<p>We are bloggers dedicated to providing high quality content/articles.</p>
<p>Check more of our content in our blog thepycodes.</p>
</div>
</body>
</html>
We will jump straight to the body since it has the same document type and HTML Tag as well as the head with only a slight difference in the head which is the title “About Us“.
Body Section:
Just like the previous HTML, it starts with a <div>
function then a heading which is the title of the page, and after that two paragraphs to introduce ourselves and invite visitors to our blog, naturally you can customize what suits your needs.
<body>
<div>
<h1>About Us</h1>
<p>We are bloggers dedicated to providing high quality content/articles.</p>
<p>Check more of our content in our blog thepycodes.</p>
</div>
</body>
</html>
Example 2
Contact HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Us</title>
</head>
<body>
<div>
<h1>Contact Us</h1>
<p>Get in touch with us via our following email:</p>
<ul>
<li>Email: contact@thepycodes.com</li>
</ul>
</div>
</body>
</html>
This one also differs only on the title in the Head section and on the information in the body section.
Body Section:
Similar to the previous two HTMLs this one starts with a heading to tell the purpose of the page, and two paragraphs to tell visitors how to contact us.
<body>
<div>
<h1>Contact Us</h1>
<p>Get in touch with us via our following email:</p>
<ul>
<li>Email: contact@thepycodes.com</li>
</ul>
</div>
</body>
</html>
Example 3
Conclusion
So, that’s the scoop on HTML templates! They’re your toolkit for making websites look good and work well. With what you’ve learned, you’re all set to bring your web ideas to life.
Happy building!