Back to basic templates | Conditional statements |
Using templates to add menus
Most websites have some form of navigation bar, to allow you to move to different parts of the website.
The problem with coding that into each page’s HTML is that if a new page or section is added, that would require a lot of code to be changed. With flask you can create a navigation template and have it included in the page.
Let’s create a template with a navigation bar, to allow us to access our home and our other page.
<html>
<head>
<!--Page title-->
<title>Website</title>
</head>
<!--page content-->
<body>
<!--Navigation bar-->
<div>Website: <a href="/index">Home</a><a href="/other">Other</a></div>
<!--Dividing line-->
<hr>
<!--Area that page content will fill-->
{% block content %}{% endblock %}
</body>
</html>
Now we need to modify our index.html file, so that it fits into the defined area.
<!--Tells the program that the main bit of HTML is in the base.html file-->
{% extends "base.html" %}
<!--The content to fit in the block defines in base.html-->
{% block content %}
<h1>{{ title }}</h1>
<p>Welcome to a webpage that's not on the web</p>
{% endblock %}
Now if we run flask we’ll see that the code from index.html is inserted into the block area in base.html.


Back to basic templates | Return to top | Conditional statements |