Django里的模板变量

变量是模板中最基本的组成单位,是视图传递给模板的数据; 当模板引擎遇到变量时,会将该变量计算为结果; 变量以{{variable}}表示,如: obj={"name":"张三","age":18}

{{obj.name}} #输出 张三 {{obj.age}} #输出 18

假设我们有一个 Django 视图函数如下:

javascript 复制代码
from django.shortcuts import render

def profile(request):
    user_info = {
        'username': 'Alice',
        'age': 25,
        'city': 'Beijing'
    }
    return render(request, 'profile.html', {'user_info': user_info})

在这个示例中,profile 视图函数向模板传递了一个名为 user_info 的字典,其中包含了用户信息:用户名、年龄和所在城市。

接着,我们在 profile.html 模板中使用这些传递的变量进行展示:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
    <h1>User Profile</h1>
    <p><strong>Username:</strong> {{ user_info.username }}</p>
    <p><strong>Age:</strong> {{ user_info.age }}</p>
    <p><strong>City:</strong> {{ user_info.city }}</p>
</body>
</html>

在这个模板中,我们通过 {``{ user_info.username }}{``{ user_info.age }}{``{ user_info.city }} 分别显示了用户的用户名、年龄和所在城市,这些数据都来自于视图函数传递的 user_info 字典。

当用户访问 profile 视图时,Django 将渲染这个模板并将用户信息动态地填充到对应位置,最终呈现给用户的页面将显示类似如下内容

User Profile

Username: Alice

Age: 25

City: Beijing

相关推荐
2501_941111511 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
v***5653 小时前
PostgreSQL 中进行数据导入和导出
大数据·数据库·postgresql
q***72565 小时前
Redis-配置文件
数据库·redis·oracle
不可描述的两脚兽5 小时前
Redis 快记
java·数据库·redis
h***34635 小时前
【MySQL】表的基本操作
数据库·mysql·oracle
SelectDB6 小时前
为什么实时更新场景下 Doris 查询性能是 ClickHouse 的 34 倍
数据库
n***63276 小时前
MySQL数据库的数据文件保存在哪?MySQL数据存在哪里
数据库·mysql
SelectDB7 小时前
从 Flink 到 Doris 的实时数据写入实践——基于 Flink CDC 构建更实时高效的数据集成链路
数据库
普通网友7 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
百锦再7 小时前
第17章 模式与匹配
开发语言·后端·python·rust·django·内存·抽象