4

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Is there any way to choose the name based on a boolean, since I believe it has to be the first thing in the file.
I think i don't understand your problem exactly but what you can do is something along these lines: template_name = 'main.html' if x else 'alt.html' where x is your boolean.
for booleans, you can use yesno directly in the template. {% extends boolean_value|yesno:"template_if_true.html,template_if_false.html" %}
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.