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

相关推荐
玉衡子10 分钟前
MySQL基础架构全面解析
数据库·后端
梦中的天之酒壶12 分钟前
Redis Stack扩展功能
数据库·redis·bootstrap
GreatSQL20 分钟前
GreatSQL分页查询优化案例实战
数据库
Leo.yuan43 分钟前
不同数据仓库模型有什么不同?企业如何选择适合的数据仓库模型?
大数据·数据库·数据仓库·信息可视化·spark
麦兜*1 小时前
MongoDB 6.0 新特性解读:时间序列集合与加密查询
数据库·spring boot·mongodb·spring·spring cloud·系统架构
chat2tomorrow1 小时前
数据采集平台的起源与演进:从ETL到数据复制
大数据·数据库·数据仓库·mysql·低代码·postgresql·etl
稻草人想看远方1 小时前
关系型数据库和非关系型数据库
数据库
考虑考虑1 小时前
Postgerssql格式化时间
数据库·后端·postgresql
千里码aicood1 小时前
【springboot+vue】党员党建活动管理平台(源码+文档+调试+基础修改+答疑)
java·数据库·spring boot
TDengine (老段)2 小时前
TDengine 选择函数 Max() 用户手册
大数据·数据库·物联网·时序数据库·tdengine·涛思数据