Add a nav bar to all templates

后端 未结 3 2028
执笔经年
执笔经年 2021-02-13 14:20

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

3条回答
  •  鱼传尺愫
    2021-02-13 14:54

    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

    
    
        
            
            {% block title %} - My Site {% endblock %}
        
        
            
    Navbar
    {% block content %}{% endblock %}

    index.html

    {% extends 'base.html' %}
    
    {% block content %}
    

    {% block title %}Home{% endblock %}

    Hello, World!

    {% 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.

提交回复
热议问题