首页 > 解决方案 > 如何在 django 中创建基本布局文件

问题描述

templates文件夹中我有 2 个 HTML 文件index.htmladd.html文件,我想创建一个布局文件并想在其中添加页眉和页脚,在中间内容中我想将我的 2 个文件覆盖到该布局文件中,任何人都可以帮忙我用这个?

这是我的 2 个 html 文件:

索引.html:

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">

<table>
    <tr>
        <th>Page Title</th>
        <th>Update Date</th>
        <th>Action</th>
    </tr>
    {% if pagelist %}
        {% for page in pagelist %}
            <tr>
                <td>{{ page.title }}</td>
                <td>{{ page.updated_date }}</td>
                <td><a href="{% url 'crud:update' page.id %}">Edit</a></td>
            </tr>
        {% endfor %}
    {% else  %}
            <tr>
                <td colspan="2">Np Pages are available</td>
            </tr>
    {% endif %}
</table>

添加.html:

{% load static %}



<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">

<form method="post" action="{% url 'crud:add' %}" name="page_form" id="page_form">
    <input type="text" name="title" value="{{ title }}">
    <input type="text" name="permialink" value="{{ permialink }}">
    <input type="text" name="updated_date" value="">
    <input type="text" name="bodytext" value="">
    <input type="hidden" name="pages_id" value="{{ page_id }}">
    {% csrf_token %}
    <input type="submit" name="submit" value="Submit">
</form>

标签: pythondjango

解决方案


按照本教程进行操作,例如:

base.html

<body>
    <div class="page-header">
        <!-- your header here -->
    </div>
    <div class="content container">
        <div class="row">
            <div class="col-md-8">
            {% block content %}
            {% endblock %}
            </div>
        </div>
    </div>
    <div class="page-footer">
        <!-- your footer here -->
    </div>
</body>

然后index.html可以扩展base.html如下:

索引.html

{% extends 'base.html' %}

{% block content %}
    <table>
    <tr>
        <th>Page Title</th>
        <th>Update Date</th>
        <th>Action</th>
    </tr>
    {% if pagelist %}
        {% for page in pagelist %}
            <tr>
                <td>{{ page.title }}</td>
                <td>{{ page.updated_date }}</td>
                <td><a href="{% url 'crud:update' page.id %}">Edit</a></td>
            </tr>
        {% endfor %}
    {% else  %}
            <tr>
                <td colspan="2">Np Pages are available</td>
            </tr>
    {% endif %}
</table>
{% endblock %}

请注意,您可以添加更多块,这些块可以在base.html模板中覆盖以渲染jscss内部头部等..)。

一旦掌握并且可以在子模板中覆盖它们blocks of code的事实,这很容易

add.html对模板做类似的事情


推荐阅读