In this chapter, we will focus on adding a navbar with links to the other pages, so that we don’t have to keep typing the URL for the pages.
Let’s create a file called base.html in the templates folder, which will serve as our parent template which means that we’ll pass this template to other pages since it has common elements for all pages such as a navbar.
When we style the website, we will include a fully functional navbar. For now, let’s just display the links for the other pages at the top, so that users can navigate the website easily.
Homepage with Navbar
Open base.html and add the following code.
We have added the nav tags here for our navigation bar.
The a tags are used to define the hyperlinks for the different pages of the website.
%block name% - %endblock name%
The block tags are tags that can be filled in by child templates. In this example, we use %block content% and %endblock content%. The content that goes inside these tags will be filled in by what we define in the other pages.
Let’s see an example of how to use the block tags by opening the index.html template and adding the following code.
% extends “parent_template” %
The extends tag tells Django from which parent template the child template is inheriting from. In this case, base.html template is the parent template from which the child templare index.html inherits from.
The extends tag takes from the parent template (base.html) the navbar and an empty pair of content block tags. The same content block tags are present in the child template. These tags wrap the information that we want to display, so now the empty tags in our parent template will contain the information from the child template content block tags.
Every page displays different information, so we have to wrap the information in the child template with the content block tags and add the extends tag in order to have a navbar in all the pages.
Listings Page with Navbar
Open all_listings.html and add the following code.
Notice that the child template information inside the content block tags hasn’t changed. I included some of it as a reference, so you know what template we are editing. I use the (…) to let you know that there’s more code in between.
New Listing Page with Navbar
Finally, let’s open new_listing.html and add the same code we’ve been adding to the other templates.
Check that all links work and that you can navigate easily between pages before moving forward.
If you're enjoying the series and want to support, you can find the entire book below.