【问题标题】:Django: Place a Python function into all pages with neat codeDjango:使用简洁的代码将 Python 函数放入所有页面
【发布时间】:2020-06-18 07:08:47
【问题描述】:

我是 Python 和 Django 的新手,所以我有这些代码:

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about', views.about, name='about'),
    path('contact', views.contact, name='contact')
]

views.py

menus = [
    {
        "name": "Home",
        "link": "/"
    }, {
        "name": "About",
        "link": "/about"
    }, {
        "name": "Contact",
        "link": "/contact"
    },
]

def gnavi():
    return {'menus': menus}

gnavi.html

<nav class="gnavi">
    <ul>
        {% for menu in menus %}
        <li>
            <a href="{{menu.link}}">
                {{menu.name}}
            </a>
        </li>
        {% endfor %}
    </ul>
</nav>

base.html

{% load static %}<!DOCTYPE html>
<html lang="en">
<head>...</head>
<body>

<header class="header">
    {% include 'inc/gnavi.html' %}
</header>
<main>
  {% block content %}
  {% endblock content %}
</main>
<footer>...</footer>

</body>
</html>

Template Structure:

+ templates
  + inc
    - base.html
    - gnavi.html
  - home.html
  - about.html
  - contact.html
  - ...

如何将 "gnavi.html" 放置到每个页面,而不是每次都在 "def" 中调用它?

# ! Problem: This code works but needs to be called each time a new page is added !
# -> Which is not very nice !

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return render(request, 'home.html', gnavi())

def about(request):
    return render(request, 'about.html', gnavi())

def contact(request):
    return render(request, 'contact.html', gnavi())

????我希望代码只被调用一次,但适用于每个页面,包括将来要创建的页面。

【问题讨论】:

标签: python html django function templates


【解决方案1】:

您可以在任何想要重复的页面中使用{%extends 'gnavi.html.html'%}

例如:

base.html:

{%extends 'gnavi.html.html'%}{% load static %}<!DOCTYPE html>
<html lang="en">
<head>...</head>
<body>

<header class="header">
    {% include 'inc/gnavi.html' %}
</header>
<main>
  {% block content %}
  {% endblock content %}
</main>
<footer>...</footer>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2015-02-27
    • 2021-03-12
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多