Home > Back-end >  Django which template to extends with if block
Django which template to extends with if block

Time:10-27

I have two distincts template which must be extended in three diffrents page. Is there a solution to extends a template with if block? I tried this without success.

{% if 'project' in request.get_full_path %}
  {% extends 'index.html' %}

{% elif 'network' in request.get_full_path %}
  {% extends 'base.html' %}

{% elif 'zoneset' in request.get_full_path %}
  {% extends 'base.html' %}

{% endif %}

{% load crispy_forms_tags %}

{% block title %} Network {% endblock title %}

{% block content %}

<div class="row">
  <div class="col-md">
    <div class="card card-body">
      <h6>Update</h6>
      <form class="" action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
          {{form|crispy}}
        <input type="submit" name="" value="Update">
      </form>
    </div>
  </div>
</div>
{% endblock %}

CodePudding user response:

If you work with template inheritance, {% extends … %} [Django-doc] should be the first template tag. You can not use an {% if … %} block, nor is it a good idea to detect the parent based on the full path of the request.

You can do this in the view, and work with:

def my_view(request):
    context = { 'parent': 'index.html' }
    return render(request, 'my_template.html', context)

and then in the template use:

{% extends parent %}
…
  • Related