向所有模板添加导航栏

2024-03-29 04:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在每页都显示导航栏。在PHP中,我会编写导航栏,然后将其包含在其他页面上。我试图将导航条模板包含或扩展到其他模板中,但没有成功。它只输出“这是主页”,如何正确地将导航栏包含在每个模板中?

layout.html

<!doctype html>
<html>
    <body>
        {% block navbar %}
            <style>
                body {
                    margin: 0;
                    padding: 0;
                }

                div{
                    background: #333;
                    color: #f9f9f9;
                    width: 100%;
                    height: 50px;
                    line-height: 50px;
                    text-align: center;
                }
            </style>

            <div>NAVBAR</div> 
        {% endblock %}

        {% block content %}
        {% endblock %}
    </body>
</html>

index.html

This is the home page.
{% extends "layout.html" %}

{% block navbar %} {% endblock %}

{% block content %}
    <h1>This is the homepage!</h1>
{% endblock %}

Tags: thediv模板isstylehtmlbodycontent
3条回答

如果要在每个页面中使用相同的导航栏,则不需要layout.html中的{% block navbar %}...{% endblock %}。或者,您可能必须使用{{ super() }},如here所述。

创建一个基本模板,该模板的布局和导航对所有页面都是通用的。然后扩展此模板以创建实际页面。将块添加到可以在其他模板中重写的基模板。

base.html

<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>{% block title %} - My Site</title>
    </head>
    <body>
        <div>Navbar</div>
        {% block content %}{% endblock %}
    </body>
</html>

index.html

{% extends 'base.html' %}

{% block content %}
<h3>{% block title %}Home{% endblock %}</h3>
<p>Hello, World!</p>
{% endblock %}

注意,导航栏只是在基本模板中定义的。它不需要块,子模板中的内容将在它之后被替换。

您可以使用similar technique来控制导航栏中突出显示的项目。

你可以在每页都包括导航栏。

nav.html

<style>
    body {
        margin: 0;
        padding: 0;
    }

    div{
        background: #333;
        color: #f9f9f9;
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }
</style>

<div>NAVBAR</div> 

layout.html:注意{% include 'nav.html' %}

<!doctype html>
<html>
    <body>
    {% include 'nav.html' %}

    {% block content %}
    {% endblock %}
    </body>
</html>

index.html

{% extends "layout.html" %}

{% block content %}
    <h1>This is the homepage!</h1>
{% endblock %}

有时候,这是设计网页的好方法。您将页面拆分为,例如:head.html、nav.html、footer.html。。。您可以将它们包含在layout.html中以使用它们。

相关问题 更多 >