Home > Blockchain >  Filling a template slot, content doesn't appear
Filling a template slot, content doesn't appear

Time:11-26

In my folder Templates I created 2 html files:

  • main.html
  • user.html

The structure of the main.html is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DJANGO</title>
</head>
<body>

    {% block userinfo %}
        
    {% endblock userinfo %}
</body>
</html>

The structure of the user.html is:

{% extends "main.html" %}

{% block userinfo %}
  <h2>John Doe</h2>
  <p>Explorer of life.</p>
{% endblock userinfo %}         

I don't understand why

<h2>John Doe</h2>
  <p>Explorer of life.</p>

doesn't appear in the browser when I call main.html

I have tried writing in this way too

{% extends "main.html" %}

{% block userinfo %}
  <h2>John Doe</h2>
  <p>Explorer of life.</p>
{% endblock %}         

without user in the endblock but it does not work.

In settings.py file in Templates list and DIR list I added:

os.path.join(BASE_DIR,'templates'),

and I importend os too.

In views.py file that I've created I have written


from django.shortcuts import render
from django.http import HttpResponse
def main(request):
    return render(request,'main.html')

In urls.py file that I've created I have written

from django.urls import path
from . import views
urlpatterns = [
    path('main/',views.main,name='')
]

When I call the page with http://localhost:8000/main/ I don't have any error. The only problem is that the page is blank. And If I try to add some text in main.html it appers on the screen, but the content from user.html doesn't appear.

Can someone help me?

CodePudding user response:

When you render main.html directly, your user.html gets ignored. If you render user.html from django, you will get expected result.

To inject user.html contents to main.html you should use something like {% include "user.html" %} insead of blocks statement.

CodePudding user response:

Extension in templates follows the same logic that class inheritance, it goes the way down not up.

Once said, main is the base template and you will never see the content of templates in which you are extending, its the opposite, you will see the content of the base template (the one you are extending for) in the child template (the one that has the extends).

I guess the behavior that you are expecting to have is the one that gives the include tag

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DJANGO</title>
</head>
<body>
    {% include "user.html" %}
</body>
</html>

user.html

  <h2>John Doe</h2>
  <p>Explorer of life.</p>
  • Related