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

相关推荐
qq_529835351 分钟前
对计算机中缓存的理解和使用Redis作为缓存
数据库·redis·缓存
月光水岸New2 小时前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu
狄加山6752 小时前
数据库基础1
数据库
我爱松子鱼2 小时前
mysql之规则优化器RBO
数据库·mysql
chengooooooo3 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
Rverdoser4 小时前
【SQL】多表查询案例
数据库·sql
Galeoto4 小时前
how to export a table in sqlite, and import into another
数据库·sqlite
人间打气筒(Ada)4 小时前
MySQL主从架构
服务器·数据库·mysql
leegong231114 小时前
学习PostgreSQL专家认证
数据库·学习·postgresql
喝醉酒的小白4 小时前
PostgreSQL:更新字段慢
数据库·postgresql