Django模板引擎如何使用?

访客 全栈框架 1

本文目录导读:

  1. 基本配置
  2. 创建模板文件
  3. 视图函数中渲染模板
  4. 模板语法详解
  5. 模板继承
  6. 包含其他模板
  7. 模板缓存
  8. 常用技巧
  9. 性能优化

Django模板引擎是Django框架的核心组件之一,用于将动态数据嵌入到HTML页面中,以下是详细的使用指南:

基本配置

settings.py中配置模板目录:

# settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # 模板目录
        'APP_DIRS': True,  # 是否在app内查找模板
        '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',
            ],
        },
    },
]

创建模板文件

templates目录下创建HTML文件,例如index.html

<!DOCTYPE html>
<html>
<head>{{ title }}</title>
</head>
<body>
    <h1>欢迎来到{{ site_name }}</h1>
    <p>当前用户:{{ user.name }}</p>
</body>
</html>

视图函数中渲染模板

# views.py
from django.shortcuts import render
def index(request):
    context = {
        'title': '首页',
        'site_name': '我的网站',
        'user': {'name': '张三', 'age': 25}
    }
    return render(request, 'index.html', context)

模板语法详解

1 变量输出

<!-- 基本变量 -->
{{ variable }}
<!-- 字典属性 -->
{{ dict.key }}
<!-- 对象属性 -->
{{ object.attribute }}
<!-- 列表索引 -->
{{ list.0 }}
<!-- 默认值 -->
{{ variable|default:"默认值" }}

2 标签(Tags)

<!-- if语句 -->
{% if user.is_authenticated %}
    <p>欢迎回来,{{ user.username }}</p>
{% elif user.is_anonymous %}
    <p>请登录</p>
{% else %}
    <p>未知状态</p>
{% endif %}
<!-- for循环 -->
{% for item in items %}
    <li>{{ item.name }} - {{ forloop.counter }}</li>
{% empty %}
    <li>没有数据</li>
{% endfor %}
<!-- 循环变量 -->
{% for item in items %}
    {{ forloop.counter }}  <!-- 从1开始计数 -->
    {{ forloop.counter0 }} <!-- 从0开始计数 -->
    {{ forloop.first }}    <!-- 第一个元素时为True -->
    {{ forloop.last }}     <!-- 最后一个元素时为True -->
    {{ forloop.revcounter }} <!-- 从末尾开始计数 -->
{% endfor %}

3 过滤器(Filters)

<!-- 常用过滤器 -->
{{ text|lower }}           <!-- 转为小写 -->
{{ text|upper }}           <!-- 转为大写 -->
{{ text|title }}           <!-- 标题格式 -->
{{ text|truncatechars:10 }} <!-- 截取前10个字符 -->
{{ text|linebreaks }}      <!-- 转换换行符为<br> -->
<!-- 日期过滤 -->
{{ date|date:"Y-m-d H:i:s" }}
{{ date|date:"Y年m月d日" }}
<!-- 数字过滤 -->
{{ number|floatformat:2 }} <!-- 保留2位小数 -->
{{ number|filesizeformat }} <!-- 文件大小格式 -->
<!-- 字符串连接 -->
{{ list|join:", " }}       <!-- 用逗号连接 -->
<!-- URL处理 -->
{{ url|urlize }}           <!-- 自动生成链接 -->
{{ text|safe }}            <!-- 标记为安全的HTML -->

4 注释

{# 单行注释 #}
{% comment %}
多行注释
可以包含多行内容
{% endcomment %}

模板继承

1 基础模板(base.html)

<!DOCTYPE html>
<html>
<head>{% block title %}默认标题{% endblock %}</title>
    {% block extra_head %}{% endblock %}
</head>
<body>
    <header>
        {% block header %}
            默认头部
        {% endblock %}
    </header>
    <main>
        {% block content %}
        {% endblock %}
    </main>
    <footer>
        {% block footer %}
            默认底部
        {% endblock %}
    </footer>
    {% block extra_scripts %}{% endblock %}
</body>
</html>

2 子模板(child.html)

{% extends "base.html" %}
{% block title %}子页面标题{% endblock %}
{% block content %}
    <h1>内容区域</h1>
    {{ block.super }}  <!-- 显示父模板中的内容 -->
    <p>这是子模板的内容</p>
{% endblock %}
{% block extra_scripts %}
    <script src="custom.js"></script>
{% endblock %}

包含其他模板

1 使用 include

<!-- 包含其他模板 -->
{% include "header.html" %}
<!-- 传递变量 -->
{% include "components/card.html" with title="卡片标题" content="卡片内容" %}
<!-- 仅传递特定变量 -->
{% include "components/card.html" with title=item.title only %}

2 自定义标签

# templatetags/custom_tags.py
from django import template
register = template.Library()
@register.simple_tag
def current_time(format_string):
    return datetime.now().strftime(format_string)
@register.filter
def multiply(value, arg):
    return value * arg

在模板中使用:

{% load custom_tags %}
{% current_time "%Y-%m-%d" %}
{{ 5|multiply:3 }}

模板缓存

# 在视图中使用缓存模板
from django.template.loader import render_to_string
from django.core.cache import cache
def cached_view(request):
    cache_key = 'cached_template'
    content = cache.get(cache_key)
    if not content:
        context = {...}
        content = render_to_string('template.html', context)
        cache.set(cache_key, content, 3600)  # 缓存1小时
    return render(request, 'cached_wrapper.html', {'content': content})

常用技巧

1 静态文件处理

{% load static %}
<!-- CSS -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- JavaScript -->
<script src="{% static 'js/main.js' %}"></script>
<!-- 图片 -->
<img src="{% static 'images/logo.png' %}" alt="Logo">

2 URL生成

<!-- 使用URL名称 -->
<a href="{% url 'article_detail' article.id %}">查看文章</a>
<!-- 带命名空间的URL -->
<a href="{% url 'blog:article_detail' article.id %}">查看文章</a>

3 国际化

{% load i18n %}
<h1>{% trans "欢迎" %}</h1>
<p>{% blocktrans %}这是翻译内容{% endblocktrans %}</p>

性能优化

  1. 使用模板片段缓存
  2. 避免在模板中进行复杂计算
  3. 使用with标签缓存重复变量
  4. 合理使用{% spaceless %}去除空白
{% with total=items.count %}
    <p>共有{{ total }}个项目</p>
{% endwith %}
{% spaceless %}
<div>
    <p>内容</p>
</div>
{% endspaceless %}

Django模板引擎提供了丰富的功能,包括变量输出、标签控制、过滤器处理、模板继承等,掌握这些功能可以显著提高Web开发效率,使代码更清晰、更易维护,记住模板引擎的目标是保持简单,复杂的业务逻辑应该放在视图或模型中处理。

标签: 模板变量

抱歉,评论功能暂时关闭!