Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 361
sinθ Avatar asked Feb 15 '23 22:02

sinθ


1 Answers

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.

like image 191
arie Avatar answered Feb 18 '23 15:02

arie