Skip to content
Advertisement

Django Template Aren’t Loading

I’m trying to load different html files into the base.html and they’re not showing. Any ideas?

<body class="bg">
   <main class='text'>
      {% block carousel %}
      {% endblock %}

      {% block info%}
      {% endblock %}

      {% block content %}
      {% endblock %} 
           
      {% block mobile %}
      {% endblock %}
    </main>
</body>

Advertisement

Answer

I think you may be confusing template inheritance with template composition.

In template inheritance, you have a base page like base.html:

<body class="bg">
   <main class='text'>
      {% block carousel %}
      {% endblock %}

      {% block info%}
      {% endblock %}

      {% block content %}
      {% endblock %} 
           
      {% block mobile %}
      {% endblock %}
    </main>
</body>

Then, you have a second template shoes.html that extends base.html. It inherits all the HTML from base.html, but fills in some custom content inside the blocks:

{% extends "base.html" %}

{% block carousel %}
<p>Carousel</p>
{% endblock %}

{% block info%}
<p>Info</p>
{% endblock %}

{% block content %}
<p>Content</p>
{% endblock %} 
           
{% block mobile %}
<p>Mobile</p>
{% endblock %}

Therefore, when you render it inside your view:

views.py

from django.shortcuts import render
def index(request):
    return render(request, 'polls/shoes.html', {})

you get this result:

<body class="bg">
   <main class='text'>
      <p>Carousel</p>
      <p>Info</p>
      <p>Content</p>
      <p>Mobile</p>
   </main>
</body>

I suspect that you have different HTML files named after each block (e.g. carousel.html, info.html). That’s not how Django works (but it is how Ruby on Rails works). Is that what you were trying to do? If not, please update your question to clarify.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement