Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django inject data after base.html

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

<body>
    <div class="wrapper">
        <nav id="sidebar">
            <div class="sidebar-header">
                <h3>Welcome!</h3>
            </div>
    
            <ul class="list-unstyled components">
                <li class="active">
                    <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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{% 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?

>Solution :

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

<!--base.html-->
<body>
    <div class="wrapper">
        <nav id="sidebar">
            <div class="sidebar-header">
                <h3>Welcome!</h3>
            </div>
    
            <ul class="list-unstyled components">
                <li class="active">
                    <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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading