在不加载整个页面的情况下以块形式呈现模板 [英] Render a template in block without loading the whole page

查看:95
本文介绍了在不加载整个页面的情况下以块形式呈现模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为base.html的模板,它看起来像这样简化:

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.

推荐答案

您有两种选择:Ajax或iFrames

You have a couple of choices: Ajax or iFrames

如果您使用Ajax路由,则可以在服务器端呈现模板并在Ajax响应中返回HTML:

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')

然后,您可以使用jQuery或任何需要更新主页中HTML的地方.

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

或者,您可以使用JavaScript设置单击时iFrame的src以呈现视图,而无需更新整个页面.就用户体验,维护等方面而言,这仅取决于最适合您的情况.

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.

这篇关于在不加载整个页面的情况下以块形式呈现模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆