Render a template in block without loading the whole page

拜拜、爱过 提交于 2019-12-25 06:59:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21729111/render-a-template-in-block-without-loading-the-whole-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!