Saifullah khan
Saifullah khan

Reputation: 778

Django extend common variable or block in child templates

I have a common variable or block in base template that i want to extend in child templates, how can i achieve that? I have following code.

base.html

<html>
    <head>
        <title>
            {% block page_title %} {% endblock %}
        </title>
        <meta property="og:title" content="{% block page_title %} {% endblock %}" />
        ...
    </head>
<body>
<h1> {% block page_title %} {% endblock %} </h1>
...

my_page.html

{% extends 'base.html' %}

{% block page_title %}
    Page title goes here
{% endblock %}

When i run this code i get the following error 'block' tag with name 'page_title' appears more than once

Upvotes: 0

Views: 335

Answers (1)

David M.
David M.

Reputation: 2640

Whenever you find yourself wanting for a value to appear twice in a template it smells like that data should be provided in your rendering context.

There are many options for that, but the simplest is just to provide a page_title context parameter when rendering the template:

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {
        'page_title': 'Your Page Title',
    })

And then use it in your template as any other template variable: {{ page_title }}

Upvotes: 1

Related Questions