Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to duplicate data in a django template? [duplicate]

<html>
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>

    <body>
        <h1>{% block title %}{% endblock %}</h1>
    </body>
</html>

This is my template, more or less. The h1 heading is always the same as the title tag. The above snippet of code is not valid because there can't be two blocks with the same name. How do I handle this without repeating myself?


edit to clarify: I have a ton of child templates which are inherited from this one template, and so making a new {{title}} variable for each template is not a very good solution. Previously I had it set up like this:

base.html:

<title>{% block title %}{% endblock %}</title>

then in base_view.html (extending base.html):

<h1>{% block title %}{% endblock %}</h1>

then in base_object.html (extending base_view.html):

{% block title %}my title goes here{% endblock %}

and it just worked somehow. I refactored my templates so theres just base.html, and base_object.html How can I get this functionality back?

like image 271
priestc Avatar asked Jul 24 '09 16:07

priestc


1 Answers

In base.html:

<head>
  <title>{% block title %}{% endblock %}</title>
</head>

<body>
  <h1>{% block h1 %}{% endblock %}</h1>
</body>

Then, make another "base" layer on top of that called content_base.html (or something):

{% extends "base.html" %}

{% block h1 %}{% block title %}{% endblock %}{% endblock %}

Now have all your other templates extend content_base.html. Whatever you put in block "title" in all your templates will go into both "title" and "h1" blocks in base.html.

like image 182
hopti Avatar answered Oct 14 '22 17:10

hopti