Change dynamic inheritance of Django templates?

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

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

I am also open to other template languages ​​that can do this.

+4
source share
2 answers

If you check the documents , you will see that extends also accepts a variable.

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

That way, you can easily identify the appropriate base template in your view and pass it into your template.

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

+5
source

Django allows you to display the contents of parent template blocks using {{ block.super}} .

This allows you to embed the contents of the parent block.

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

block.super was designed to allow you

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

+2
source

Source: https://habr.com/ru/post/1491699/


All Articles