【问题标题】:How to extends and include in organizing django templates?如何扩展和包含在组织 django 模板中?
【发布时间】:2019-03-05 21:36:51
【问题描述】:

我的 django 模板文件夹中有这样的代码:

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {% block home %} {% endblock home %}
</body>
</html>

top.html

<div id="top">
    <h1>This is the navbar content</h1>
</div>

left.html

<div id="left">
    <p>This is the menu content</p>
</div>

现在我想将这些模板中的每一个都包含到这样的主模板中

home.html

{% extends "myapp/base.html" %}

{% block home %}
{% include "myapp/top.html" %}
{% include "myapp/left.html" %}
{% endblock home %}

这是我在 views.py 中的渲染函数 视图.py

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

但是当我运行服务器时,'home.html' 中的 include 语句不起作用。怎么回事?

谢谢。

【问题讨论】:

    标签: django django-templates include extends


    【解决方案1】:

    enter image description here

      home.html
      {% extends "base.html" %}
    
      {% block home %}
      {% include "top.html" %}
      {% include "left.html" %}
      {% endblock home %}
     views.py
      def home(request):
          return render(request, 'home.html')
     urls.py (in your apps)
    
      from django.urls import path
      from .import views
    
      urlpatterns = [
    
      path('', views.home),
      ]
    
     urls.py (in your main folder)
      from django.contrib import admin
      from django.urls import path, include
    
     urlpatterns = [
     path('admin/', admin.site.urls),
     path('', include('your app name.urls')),
     ]
    

    它必须工作 1000%,其他 html 文件相同

    【讨论】:

      猜你喜欢
      • 2010-11-27
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2017-04-24
      相关资源
      最近更新 更多