【发布时间】: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())
????我希望代码只被调用一次,但适用于每个页面,包括将来要创建的页面。
【问题讨论】:
-
你可以使用[上下文处理器] (docs.djangoproject.com/en/3.0/ref/templates/api/…)
-
-感谢您提供链接部分。 + RequestContext 是关键字 - 这个视频解释了所有这些youtu.be/_eWLaL2g1bo - 这个问题已经解决了!
标签: python html django function templates