Martin
Martin

Reputation: 4330

How to set block name dynamically in django template?

For easier template inheritance, I want to determine the name of a parents {% block %} name dynamically.

For this I have two parent templates. The main one is like this

# main parent
...
{% block details %}{% endblock %}
...

And the other one:

# other parent
...
{% block content %}{% endblock %}
...

Because this templates are use very often and a change in block naming would cause a lot work, I tried something with a boolean main_template indicating which block name to use in the child template:

# child template
...
{% block main_template|yesno:'details,content' %}
...
{% endblock %}
...

This does not work. Is there some other way to get the behaviour I described?

Upvotes: 1

Views: 1219

Answers (1)

Ian Clelland
Ian Clelland

Reputation: 44122

No, this won't work -- the argument to {% block %} is a label, not a value, so you can't use a context variable there.

There might be some ways to work around this, but they're not going to be maintainable. Honestly, it would probably be better to put the effort in (this should really just be a search&replace operation) to align the block names between the different base templates.

The way that Django template inheritance works, child templates need to have knowledge of the block structure of their parent template. If you have a child template that can inherit from several different parents, then they really all need to have the same structure.

Upvotes: 1

Related Questions