django html模板继承 {%block 标记名} {%endblock%}

对于url文件

   url(r'^tp1/', views.tp1)

对于views文件,跳转到tp1.html 同时将list列表传到前端

def tp1(request):
    list = [1, 2, 3, 4, 5, 6]
    return render(request, 'tp1.html', {'list': list})

对于被继承的文件master, 通过写入{%block 标记%}{%endblock%}里面的内容将是被替代的内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="/static/commons.css">
<style>
    .pg-content{
        height: 48px;
        line-height: 48px;
        text-align: center;
        color: red;
        background-color: white;
    }
</style>
</head>
<body>
    <div class="pg-content">小男孩管理</div>
    {% block content %}{% endblock %}

<script src="/static/jquery-3.3.1.js"></script>
</body>
</html>

继承者tp1  首先通过{% extends 'master.html' %} 导入 master.html 

然后在{%block 标记%}{%endblock%}中填入值,及master中需要被代替的内容

标记需要一一对应

{% extends 'master.html' %}
{% block title %}老男孩管理{% endblock %}
{% block content %}
    <ul>
    {% for i in list %}
        <li>{{ i }}</li>
    {% endfor %}
    </ul>

{% endblock %}

猜你喜欢

转载自www.cnblogs.com/my-love-is-python/p/9459603.html