Django-7-模板层变量和标签

模板层变量

视图层能向模板传递哪些数据,其实python中所有数据类型都可以,str、int、list、tupple、dict、function以及class,在模板中的调用方法如下

  • 首先在视图函数中定义不同的数据类型
def test_html(request):
    from django.shortcuts import render

    def fun():
        return "This is a function"

    class class_obj:
        def fun(self):
            return "This is a function of a class"

    dic = {}
    dic['str'] = 'str'
    dic['int'] = 18
    dic['list'] = ['list', 'i', 1]
    dic['tup'] = ('tupple', 'i', 1)
    dic['d'] = {'name': 'Django', 'language' : 'python'}
    dic['fun'] = fun
    dic['class'] = class_obj

    return render(request, 'test.html', dic)
  • 然后在模板中调用数据
<body>
    <h1>str: {{ str }}</h1>
    <h1>int: {{ int }}</h1>
    <h1>list: {{ list }}</h1>
    <h1>list[0]: {{ list.0 }}</h1>
    <h1>tup: {{ tup }}</h1>
    <h1>tup[0]: {{ tup.0 }}</h1>
    <h1>dic: {{ d }}</h1>
    <h1>dic['name']: {{ d.name }}</h1>
    <h1>fun: {{ fun }}</h1>
    <h1>class: {{ class }}</h1>
    <h1>class.fun: {{ class.fun }}</h1>
</body>

从上面可以看到,想要调用视图函数的变量非常简单,只需要在{{}}中写上render函数中引用字典中键名即可,如果值是list和tupple需要注意想要取具体元素是通过list.index的形式(例如list.0,list.1…),如果是字典和类,则是通过dic.key或者class.method,注意没有括号;函数即函数名
在这里插入图片描述

模板标签

  • 作用:将服务器功能嵌入到模板层,例如流程控制
  • 标签语法:
{% 标签 %} # {% if %}
...
{% 结束标签 %} # {% endif %}
  • 需要注意的是,if/for等与python语法基本一致,只是需要在末尾添加结束标签,另外没有冒号结构
  • <,>,==,!=,>=,<=,in,not in,is ,is not, and ,or, not都是可以使用的
  • 但是if中的括号是无效的不能设定优先级,若需要使用优先级需要使用嵌套的if标签
  • if标签示例:
    views.py
def test_if(request):
    dic = {}
    dic['a'] = 100
    return render(request, 'test_if.html', dic)

test_if.html

<body>
    {% if a == 100 %} # 在标签引用视图变量直接写变量名即可,不要双大括号
    <h2>a就是100</h2>
    {% elif a < 100 %} 
    <h2>a小于100 </h2>
    {% else %} 
    <h2>a 大于100 </h2>
    {% endif %}
</body>
  • for标签
{% for 变量 in 可迭代对象 %}
... 循环语句
{% empty %}
... 可迭代对象为空时填充语句
{% endfor %}

示例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    {% for i in age %}
    <p>age is {{ i }}</p>
    {% endfor %}
</body>

</html>

views.py

def test_for(request):

    dic = {}
    dic['age'] = [10, 20, 30, 40, 50]
    return render(request, 'test_for.html', dic)

参考

达内教育

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值