Reputation: 5627
Django beginner. I have a base template with a logo, and three subsections for content. Two of the subsections contain html by default, and the remaining subsection is for the content of each child page.
I would now like to create a different page, with the exact same logo, but with different subsections / content. e.g. I may want just two subsections, formatted horizontally instead of vertically etc.
So, for this I guess I need to create a new template - the problem is I am violating the DRY principal by having the exact same logo html code in the new template as the first template.
So, are there any design patterns to resolve this issue of repeating the logo code in this case ? I was thinking about having variables like isPage1
or isPage2
passed to the template, and then I would enable/disable blocks based on this - is this a feasible method, and can anyone provide any alternatives ?
Many thanks
Upvotes: 1
Views: 639
Reputation: 138
You can use this inheritance concept in different way.
use same block tags to whole application
filename: index.html
<html>
<head>
---style.css files here---
{% block title %}title{% endblock %}
{% block additional_css_files %}css files{% endblock %}
{% block header %}header and header menus{% endblock %}
</head>
<body>
{% block main_content %}
your body content here
{% endblock %}
{% block scripts %}Script files{% endblock %}
</body>
</html>
filename: home.html
{% extends "index.html" %}
{% block title %}title2{% endblock %}# u can overwrite the title with new title
but if you want to use parent title no need to mention block tags in home.html
or you have to use {% block title %}{{block.super}}{% endblock %}
same concept come below.
{% block additional_css_files %}css files2{% endblock %}
{% block header %}header and header menus{% endblock %}
Upvotes: 0
Reputation: 181270
Yes, there is a pattern that exactly fits your needs. It's called template inheritance in DJANGO.
You will basically have a base template with your header, logo, and main content placeholder. Something like (extracted from the link I placed above):
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
Then, on your actual web page (the one using the template) you will have:
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
Note that the base template here is called base.html
. So, in your web page you extend base.html
by placing {% extends "base.html" %}
. Then, in that page, you just add content for specific block
.
Upvotes: 6