rohithpr
rohithpr

Reputation: 6330

How do you make use of multiple templates when you are loading a page using Django?

Suppose the layout of the pages that I want to load are of the form:

a)

<p>Hello</p>    -- varies
<h1>World</h1>    -- fixed
<h6>foo</h6>      -- varies

b)

<h2>Hey</h2>
<h1>World</h1>
<h2>bar</h2>

and so on, where some part of the page is common to all the pages (say, the part with the banner, search box etc.) but the layout of other parts are different.

Is there a way to combine multiple templates without having to copy-paste the common parts to each file?

PS: Using Django1.7 and Python 3.4 on a Win8 PC.

Upvotes: 0

Views: 63

Answers (1)

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

you can use 2 solutions:

1-use extends:

define base.html template like this:

<p>{% block var1 %}{% endblock %}</p>    -- varies
<h1>World</h1>    -- fixed
<h6>{% block var2 %}{% endblock %}</h6>      -- varies

and use base.html like this:

a):

{% extends "base.html" %}
{% block var1 %}Hello{% endblock %}
{% block var2 %}foo{% endblock %}

b):

{% extends "base.html" %}
{% block var1 %}Hey{% endblock %}
{% block var2 %}bar{% endblock %}

2- use include:

define fix.html:

<h1>World</h1>

and use it like this:

a):

<p>Hello</p>    -- varies
{% include "fix.html" %}
<h6>foo</h6>      -- varies

b):

<p>Hey</p>    -- varies
{% include "fix.html" %}
<h6>bar</h6>      -- varies

Upvotes: 3

Related Questions