Home > Software engineering >  Django inject data after base.html
Django inject data after base.html

Time:08-24

I have a base.html file which is a side bar menu. like this:

<body>
    <div >
        <nav id="sidebar">
            <div >
                <h3>Welcome!</h3>
            </div>
    
            <ul >
                <li >
                    <a href="#list">List</a>
                </li>
                <li>
                    <a href="#">Item 1</a>
                </li>
                <li>
                    <a href="#">Item 2</a>
                </li>
            </ul>
        </nav>
    </div>
</body>

I also have a text file that I want to show the content. So I configured my view like this:

def list(request):
    f = open('textFile.txt', 'r')
    file_content = f.read()
    f.close()
    context = {'file_content': file_content}
    print(file_content)
    return render(request, "list.html", context)

The destination HTML file which is going to show the data is like this:

{% extends 'base.html' %}

{{ file_content }}

The problem is, the text file data is now showing up. and if I remove {% extends 'base.html' %} them the text file data shows up, but I lose the side bar. How can I resolve this issue?

CodePudding user response:

You should define some blocks to override using Django's template inheritance:

<!--base.html-->
<body>
    <div >
        <nav id="sidebar">
            <div >
                <h3>Welcome!</h3>
            </div>
    
            <ul >
                <li >
                    <a href="#list">List</a>
                </li>
                <li>
                    <a href="#">Item 1</a>
                </li>
                <li>
                    <a href="#">Item 2</a>
                </li>
            </ul>
        </nav>
        <main>
            {% block content %}{% endblock %}
        </main> 
    </div>
</body>


<!--list.html-->
{% extends 'base.html' %}

{% block content %}{{ file_content }}{% endblock %}

CodePudding user response:

You need to use {% block %} in your base.html. Then when you extend your template, you can specify that file_content goes in the block. E.g.:

base.html

<div>Sidebar</div>
{% block after_sidebar %}{% endblock %}

destination file:

{% extends 'base.html' %}
{% block after_sidebar %}
    {{ file_content }}
{% endblock %}

See more in Django Docs - Template Inheritance

CodePudding user response:

please read carefully about "extend" https://docs.djangoproject.com/en/4.1/ref/templates/language/#templates

in your base.html you should have any blok's tags ( {% block 'myname' %}{% endblock 'myname' %}), which you should to extend.

<-- base.html -->
<body>
    <div >
        <nav id="sidebar">
            <--  ... any staff here --> 
        </nav>
        {% block 'myname' %}{% endblock 'myname' %}
    </div>
</body>

after that:

<-- your template -->
{% extends 'base.html' %}
{% block 'myname' %}{{ file_content }}{% endblock 'myname' %}
  • Related