ThaPhil
ThaPhil

Reputation: 3

Render a template in block without loading the whole page

I have a template called base.html which looks simplified like this:

<html>
<head>
    <title>{% block title %} Title {% endblock %}</title>
</head>
<body>
    <div class="header">
        {% block header %}My Header{% endblock %}
    </div>

    <div class="navigation">
        {% block navigation %}My Navi{% endblock %}
    </div>

    <div class="content">
        {% block content %}Content{% endblock %}
    </div>
</body>
</html>

When i click on a link in the nav i want to render the new content in the content block without loading the header and navigation again.

Upvotes: 0

Views: 3228

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34583

You have a couple of choices: Ajax or iFrames

If you go the Ajax route, you can render a template server-side and return the HTML in the Ajax response:

import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def render_template(request):
    result = {'html': render_to_string('your-template.html', {})}
    return HttpResponse(json.dumps(result, ensure_ascii=False),
        content_type='application/json')

Then you can use jQuery or whatever you want to update the HTML in the main page wherever you need.

Alternatively, you can use JavaScript to set the src of an iFrame on click to render a view without updating the entire page. It just depends on what's best for you in terms of user experience, maintenance, etc.

Upvotes: 1

Related Questions