Home > Net >  Passing a variable to include in extends in Django templates
Passing a variable to include in extends in Django templates

Time:01-03

I have the following structure of templates:

main.html

<html>
<body>
  <p>
    This works: {% block title %}{% endblock %}
  </p>

  {% include 'heading.html' with title=title %} {# but this does not work since it is not a variable #}
</body>
</html>

heading.html

<p>
  {{ title }}
</p>

page.html

{% extends 'main.html' %}

{% block title %}test title{% endblock %}

How can I pass the title from page.html to heading.html? Ideally, it should be defined as a block like now, but alternatives are also welcome. I'd like to contain the solution within the templates if possible.

CodePudding user response:

One possible solution is to split heading.html into two and add a {% block %} in-between, but this is an ugly workaround that is prone to bugs with unclosed tags.

I am searching for a better alternative.

main.html

...
{% include 'heading1.html' %} {# containing <p> #}
{% block title %}{% endblock %}
{% include 'heading2.html' %} {# containing </p> #}
...

Additionally, if white spaces are important, there has to be no new line between includes and the block.

CodePudding user response:

instead of {% include %}, you might want to use custom template tags with returning html or extension like slippers

  • Related