Go to templates directory and create base.html, with this content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<a href="{% url 'home' %}">Home</a> | <a href="{% url 'about' %}">About</a> | <a href="{% url 'contact' %}">Contact</a> |
</body>
</html>
Basically, we are creating base template with navigation so that all other custom page (home, about, contact) can inherit from it.
Now, in every custom page, for example home.html, we need to import base.html:
{% extends 'base.html' %}
<h1>Heading in home.html</h1>
But if you check http://127.0.0.1:8000 for homepage, there's only content from base template there, and not custom stuff from home.html
Solution is to create sections (blocks) in base template, that can be substituted with custom content from each individual html page that inherits from base template:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
{% block content %}
<a href="{% url 'home' %}">Home</a> | <a href="{% url 'about' %}">About</a> | <a href="{% url 'contact' %}">Contact</a> |
{% block head %}
<h1>DEFAULT H1 That Can Be Substituted in Custom Pages, if you need that.</h1>
{% endblock %}
{% endblock %}
</body>
</html>
Now when we visit homepage (site "root", or home.html) we will have default situation, where H1 Heading will be visible. Or any other content from base.html, not just navigation.
But, important thing is that we can have custom content in all individual html pages - and that content will be actually visible:
Code in home.html, for example:
{% extends 'base.html' %}
{% block head %}
<h1>Custom H1 Heading from home.html</h1>
<p>Custom paragraph from home.html</p>
<p>Navigation is still provided by base template, base.html</p>
{% endblock %}
In Django, {% block %}
is a template tag used to define a block of content in a parent template that can be overridden by a child template that extends the parent.
It is used in the parent template to define named sections of content that can be overridden in child templates. The block tag is followed by a unique name for the block, and the contents of the block are defined within the opening and closing tags.
No comments:
Post a Comment