Django 模板语言

本文深入解析了模板语言的使用,包括深度变量查找、变量过滤器(filter)的语法与功能,如add、capfirst、cut等,以及标签(tag)的运用。通过具体示例展示了如何在网页中动态呈现数据,如日期格式化、列表展示、条件判断和循环操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.深度变量查找: "." 点号

 2.变量的过滤器filter   

      语法格式:   {{obj|filter:para}}   冒号前后不能有空格、

       filter函数:  

             add:给obj增加数值

             capfirst:首字母大写

             cut:移除字串中的指定字符

             date:格式化日期字符串

             default:如果值是False,就提换成设置的默认值,否则就用原本的值,将传过来的空字符串显示为字串,可以起到提示的作用

             default_if_none: 如果值是None,就替换成设置的默认值,否则就用本来的值

             safe:告诉浏览器这是安全的,对a标签可以渲染,不加safe,标签a就是源码显示
                    另外一个安全机制:
                        {% autoescape off %}
                                <h1>{{ a }}</h1>
                        {% endautoescape %}                        

3.标签(tag)的使用:使用大括号和百分比的组合来表示


    

#views.py

def query(request):
    l=["团长","连长","局长"]
    d={"name": "Tom","age":48,"hobby": "sleep"}

    c=Animal("lihua","female")
    test="hello world"
    test2="h ell o wo   rld"
    num=10
    t=datetime.datetime.now()
    e=[]
    a="<a href=''>click</a>"

    return render(request,"index.html",locals())

#index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>hello {{ action.0 }}</h1>
<h1>hello {{ d.name }}</h1>
<h1>hello {{ d.age }}</h1>
<h1>hello {{ c.name }}</h1>
<h1>hello {{ c.sex }}</h1>

<h1>tom的真实年纪:{{ d.age|add:12 }}</h1>

<h1>{{ test|capfirst }}</h1>

<h1>{{ test2|cut:" " }}</h1>

<h1>{{ t|date:"Y-m-d" }}</h1>

<h1>{{ e|default:"空的列表" }}</h1>
<h1>{{ a|safe }}</h1>
{% autoescape off %}
        <h1>{{ a }}</h1>
{% endautoescape %}

{% if d.age > 20 %}

    {% if d.age < 50 %}
        <h1>{{ d.name }}的年纪大于20小于50</h1>
    {% else %}
        <h1>hello {{ d.name }}</h1>

        {% endif %}
{% elif d.age > 10 %}
    <h1>{{ d.name }}的年龄大于10岁小于20</h1>
{% else %}
    <h1>{{ d.name }}的年纪小于10岁</h1>
{% endif %}

{#forloop.counter表示循环的次数,默认从1开始计数,要想从0开始计数forloop.counter0#}

{% for name in l %}
    {{ name }}
    <h1>{{ forloop.counter0 }}:{{ name }}</h1>
    <h1>{{ forloop.revcounter0 }}:{{ name }}</h1>
{% endfor %}


</body>
</html>

访问:

     在terminal中启动项目:  python  manage.py  runserver 8083

     在本地浏览器中访问:  http://127.0.0.1:8083/query

浏览器访问结果:

hello

hello Tom

hello 48

hello lihua

hello female

tom的真实年纪:60

Hello world

helloworld

2019-07-04

空的列表

click

click

Tom的年纪大于20小于50

团长

0:团长

连长

1:连长

局长

2:局长

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值