On the Django template inheritance

Summary

    由于我们以前刚开始学的时候写的HTML文件都是有特定功能的HTML片段。但在实际应用中,我们会使用 Django 创建一个完整的站点,例如一个后台管理主机管理系统,一个人员管理系统等等。 这样的系统,必定就会存在一个大体的样本框架,例如左侧菜单,头部header信息,这样的通用部分在每个页面都会存在。这就带来一个常见的 Web 开发问题: 在整个网站中,如何减少共用页面区域(比如站点导航)所引起的重复和冗余代码?

    我们不可能在每一个html中都复制粘贴这样相同的代码,就算你想这样,那么当你想要修改这些公共区域呢?是否也需要到每个html中去修改相同的地方

appear

    这样就出现了我们的模板重用的需求,相同的模板,我们在其中的content中提上不同的内容就可以了

Method to realize

  • A mastermaster.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>
    <link rel="stylesheet" href="/static/commons.css">

    <style>
        .pg_header{
            height: 48px;
            background-color: seashell;
            color: green;
        }
        {% block css %} {#在这里写每个页面的自己的css#} {% endblock %}
    </style>
</head>

<body>


<h1 class="pg_header">主机管理系统-头部</h1>
<div class="menu">左侧菜单</div>

{% block content %} {#当想使用这个母版框架的html文件会被替换到这个block位置#} {% endblock %}


<script src="/static/jquery-min.js"></script>
<script>
    {% block js %} {#在这里写每个页面的自己的js#} {% endblock %}


</script>
</body>
</html>
  • Use this master
{% extends 'layout.html' %} {#声明使用那个模板中,内容就会在哪个模板中被替换#}


{% block title %}用户管理{% endblock %}
{#替换模板中的title block#}

{% block content  %}
<h1>用户管理tab</h1>
<ul>
{% for user in user_list %}
    <li>{{ user }}</li>
{% endfor %}
</ul>
{% endblock %}
  • A few points to note:
    • A html file can only inherit a template
    • html files defined in the template block fields need to wrap placed in the portion of the template, and at the end of {% endblock%}
    • html css and js each have their own, needs to be placed above the location marked out

How to import a single module other html files

{% include 'tag.html' %}  {#导入其他html模板中的某个组件到本模板中的当前位置#}

Guess you like

Origin www.cnblogs.com/forsaken627/p/12521975.html