You are advised to check corresponding YouTube video at the end of this article.
Ok, let's create base.html in templates directory, with this content:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<ul>
<li><a href="">Home</a></li>
<li><a href="">New Post</a></li>
<li><a href="">Admin</a></li>
</ul>
<hr>
</body>
</html>
Obviously, we need to include base.html in index.html, or any other custom page where navigation is desired:
{% extends 'base.html' %}
<h1>All Posts: </h1>
{% for post in all_posts %}
<ul>
<li>{{ post.id }} - {{ post.title }} - {{ post.text }}</li>
</ul>
{% endfor %}
But if we do that with previous code - all posts are gone because there's no dedicated block of code inside index.html for for loop.
That means, our base.html must hold some generic section, that will be used/customized inside custom html pages that inherits from base template.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<ul>
<li><a href="">Home</a></li>
<li><a href="">New Post</a></li>
<li><a href="">Admin</a></li>
</ul>
<hr>
{% block listing %}
{% endblock %}
</body>
</html>
And now we can enclose for loop inside index.html in dedicated block/section:
{% extends 'base.html' %}
<h1>All Posts: </h1>
{% block listing %}
{% for post in all_posts %}
<ul>
<li>{{ post.id }} - {{ post.title }} - {{ post.text }}</li>
</ul>
{% endfor %}
{% endblock %}
Now on index.html page we have navigation, but also all posts from our database.
No comments:
Post a Comment