Django入门二 - templates

Templates - Render Templates in Views

  • myproject/views.py: render the templates in view(在view中渲染模版)

      from django.shortcuts import render
    
      def homepage(request):
          context = {
              'title': 'Welcome to My Django App',
              'message': 'This is the homepage of my Django application.',
          }
          return render(request, 'home.html', context)
    
    • request: http request from user(用户请求).
    • home.html: path of the template(模版路径).
    • context: data passed to the template.
  • myproject/templates/home.html: A template contains static parts and some special syntax(variables and logic) describing how dynamic content will be inserted.(创建一个模版)

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          {% if title %} <!-- Check if title is provided -->
              <title>{{ title }}</title>
          {% else %}
              <title>Home</title>
          {% endif %}
      </head>
      <body>
          <h1>{{ message }}</h1>
      </body>
      </html>
    
    • Django Template Language, or DTL(模版语法):
      • use {{ variable }} to display variables, such as {{ title }},{{ user.username }}

      • use filters to change how the variable is displayed

        {{ name|lower }}
        {{ date|date:"Y-m-d" }}
        {{ content|truncatewords:50 }}
        {{ name|lower|capfirst }}
        
      • use {% %} to control structure, samples:

        if-else:

        {% if title %} 
            <title>{{ title }}</title>
        {% else %}
            <title>Home</title>
        {% endif %}
        

        for:

        <ul>
            {% for item in items %}
                <li>{{ item.name }}</li>
            {% empty %}
                <li>no program</li>
            {% endfor %}
        </ul>
        

        load other templates

        {% include "header.html" %}
        {% extends "base.html" %} 
        
  • myproject/settings.py: make sure the additional template dir is added as below for Django to locate templates(配置模版路径, 参考模版查找机制)

      TEMPLATES = [
          {
              'BACKEND': 'django.template.backends.django.DjangoTemplates',
              'DIRS': ['templates'],  # Add your templates directory here
              'APP_DIRS': True,
              'OPTIONS': {
                  'context_processors': [
                      'django.template.context_processors.debug',
                      'django.template.context_processors.request',
                      'django.contrib.auth.context_processors.auth',
                      'django.contrib.messages.context_processors.messages',
                  ],
              },
          },
      ]
    

Start the server to validate the generated html
在这里插入图片描述

Configure CSS & JS

CSS
  • myproject/static/css/style.css: define style here(定义样式)

      * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
      }
    
      body {
          min-height: 100vh;
          display: grid;
          place-content: center;
          font-size: 1rem;
          background-color: black;
          color: whitesmoke;
      }
    
      h1, p {
          text-align: center;
      }
    
  • myproject/settings.py: tell Django where’s the folder for static assets.(配置样式路径)

      STATIC_URL = 'static/'
      STATICFILES_DIRS = [
          BASE_DIR / "static",
      ]
    
  • myproject/templates/home.html link style

      <!DOCTYPE html>
      {% load static %}
      <html lang="en">
      <head>
          ...
          <link rel="stylesheet" href="{% static 'css/style.css' %}">
      </head>
      ...
    
  • start the server to validate the generated html

    在这里插入图片描述

JS
  • static/js/main.js (定义js)

    console.log('this is JS from your Home page')
    
  • templates/home.html: load js (在templates中加载 js)

    <!DOCTYPE html>
    {% load static %}
    <html lang="en">
    <head>
        ...
        <script src="{% static 'js/main.js' %}" defer></script>
    </head>
    ...
    

    defer: wait until all of the page is loaded and then it loads the script

  • validate:
    在这里插入图片描述
    static files(e.g. css, js) lookup mechanism

Summary
  1. Prepare data (context) in the view
  2. Load the desired template
  3. Render the template with the provided context
  4. Return the rendered HTML as an HTTP response

Template inheritance (模版继承)

Template inheritance lets you define a base template with placeholders (called blocks) that can be overridden by child templates. This avoids repetition of code like headers, footers, navigation bars, and other shared UI components.
(模板继承允许我们定义一个带有占位符(称为块)的基础模板,这些块可以在子模板中被覆盖。这避免了像头部、尾部、导航栏和其他共享UI组件的代码重复。)

Key Concepts
  • extends: Specifies which template the current one is inheriting from.(指定当前模板继承自哪个模板。)
  • block: Defines a section in a template that can be overridden in a child template.(在模板中定义一个可以被子模板覆盖的部分。)
Sample
  1. Create a base template()

    templates/layout.html

     <!DOCTYPE html>
     {% load static %}
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>
             {% block title %}
                 Django App
             {% endblock %}
         </title>
         <link rel="stylesheet" href="{% static 'css/style.css' %}">
         <script src="{% static 'js/main.js' %}" defer></script>
         {% block extra_css %}{% endblock %}
         {% block extra_js %}{% endblock %}
     </head>
     <body>
         <nav>
             <ul>
                 <li><a href="/">Home</a></li>
                 <li><a href="/about">About</a></li>
                 <li><a href="/myapp/posts">Posts List</a></li>
             </ul>
         </nav>
         <main>
             {% block content %}
             {% endblock %}
     </body>
     </html>
    
    • It defined 2 blocks: title, content. These blocks can be overridden in child templates.
    • {% load static %} tells django to locate and load static files
    • {% block extra_css %}{% endblock %}: child templates can override the block to load specific extra CSS files.
    • {% block extra_js %}{% endblock %}: child templates can override the block to load specific extra JS files.
  2. Child Templates that extends base template

    templates/home.html

     {% extends 'layout.html' %}
     {% load static %}
     {% block extra_css %}
         <link rel="stylesheet" href="{% static 'myapp/css/home.css' %}" />
     {% endblock %}
     {% block extra_js %}
         <script src="{% static 'myapp/js/home.js' %}" defer></script>            
     {% endblock %}
    
     {% block title %}
     {{ block.super }} - Home
     {% endblock %}
     {% block content %}
     <h1>Home</h1>
     {% endblock %}
    

    myapp/templates/myapp/posts_list.html

     {% extends 'layout.html' %}
     {% block title %}
     Posts List
     {% endblock %}
     {% block content %}
     <h1>Posts List</h1>
     {% endblock %}
    
    • {% load static %} load extra static files for child templates.
    • {% extends 'layout.html' %} tells Django to use layout.html as the parent template.
    • {% block title %} overrides the title block.
    • {% block content %} replaces the default content in the main section.
    • {{ block.super }} perserves parent content

    validate by starting server:
    在这里插入图片描述
    在这里插入图片描述

    File structure:

         .
         ├── myproject
         │   ├── myapp
         │   │     ├── templates
         │   │     │   └── myapp
         │   │     │       └── posts_list.html
         │   │     └── static
         │   │         ├── myapp
         │   │         │   ├── css
         │   │         │   │   └── home.css
         │   │         │   └── js
         │   │         │       └── home.js
         │   ├── myproject
         │   ├── static
         │   │   ├── css
         │   │   │   └── style.css
         │   │   └── js
         │   │       └── main.js
         │   └── templates
         │       ├── about.html
         │       ├── home.html
         │       └── layout.html
    
  3. Nesting multiple levels of Templates
    Sample:

  • base.html → general layout
  • section_base.html → extends base.html, defines blocks specific to a section (e.g., blog posts)
  • post_detail.html → extends section_base.html, adds post-specific content
Summary
  • {% extends %}: Used at the top of a template to inherit from another.
  • {% block %}: Defines a section that can be overridden in child templates.
  • {{ block.super }}: Includes the content of the same block from the parent template.
  • Multi-level inheritance: You can chain multiple layers of templates for advanced organization.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值