将导航栏添加到所有模板 [英] Add a nav bar to all templates

查看:48
本文介绍了将导航栏添加到所有模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个页面上显示一个导航栏.在PHP中,我会编写导航栏,然后将其包含在其他页面上.我尝试将导航栏模板包括或扩展到其他模板中,但是没有用.它仅输出这是主页".如何在每个模板中正确包含导航栏?

I want to show a nav bar on every page. In PHP, I would write the nav bar then include it on the other pages. I tried to include or extend the nav bar template into the other templates, but it didn't work. It only outputs "This is the home page." How do I correctly include the nav bar in every template?

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 %}

推荐答案

使用所有页面通用的布局和导航创建基本模板.然后扩展此模板以创建实际的页面.向基本模板中添加可以在其他模板中覆盖的块.

Create a base template with the layout and naviagation that will be common to all pages. Then extend this template to create the actual pages. Add blocks to the base template that can be overriden in the others.

base.html

<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>{% block title %} - My Site {% endblock %}</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 %}

请注意,导航栏仅在基本模板中定义.它不需要块,并且子模板中的内容将在其后被细分.

Note that the navbar is just defined in the base template. It does not need a block, and the content from the child templates will be substituded in after it.

您可以使用类似的技术来控制导航栏中突出显示的项目.

You can use a similar technique to control which item is highlighted in a navigation bar.

这篇关于将导航栏添加到所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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