sinθ
sinθ

Reputation: 11493

Change Django Template Inheritance Dynamically?

I have a template with the following: {% extends "main/main-template.html" %} I also want a template with the exact same thing, only instead it {% extends "main/main-template-quick.html" %} It seems like a violation of DRY to just copy and paste the same code into a new file, just so I can change the template. Is there any way to select the super-template dynamically?

If not, is there a good way to do the following: Reuse the same {% block %} and its content with a different template. At the same time, not violating DRY.

I'm also open to other template languages that may be able to do this.

Upvotes: 4

Views: 1648

Answers (2)

dm03514
dm03514

Reputation: 55952

Django allows for display the parent templates block content using {{ block.super}}.

This allows you to insert the parent's block contents.

{% block content %}
  {{ block.super }}
{% endblock content %}

block.super was designed to allow you to

Reuse the same {% block %} and its content with a different template.

Upvotes: 2

arie
arie

Reputation: 18972

If you check the docs you'll see that extends accepts a variable too.

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template.

So you can easily determine the appropiate base template in your view and pass it to your template.

And if you want to reuse a chunk of html in different contexts than the include tag is your friend.

Upvotes: 6

Related Questions