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

相关推荐
51714 分钟前
Django中序列化与反序列化
后端·python·django
kk在加油29 分钟前
Redis数据安全性分析
数据库·redis·缓存
DolphinDB1 小时前
更高效的因子研究工具:基于 DolphinDB 的因子评价框架详解
数据库
此乃大忽悠1 小时前
身份认证缺陷
java·数据库·webgoat·身份认证缺陷
timing9942 小时前
SQLite3 中列(变量)的特殊属性
java·jvm·sqlite
IT项目管理2 小时前
达梦数据库DMDRS搭建单向dm8-dm8数据同步
数据库
咖丨喱2 小时前
【Action帧简要分析】
服务器·数据库·asp.net
没饭吃!2 小时前
NHibernate案例
数据库·hibernate
泷羽Sec-静安3 小时前
OSCP官方靶场-Solstice WP
服务器·网络·数据库
IvanCodes3 小时前
Oracle 视图
大数据·数据库·sql·oracle