6.模板语言

我们在写django项目时,前端难免要用到后台的数据,但前后端的语言又不通用,有了模板语言后台可以把数据交给前端进行渲染。
django模板语言要记两种,变量{{ }}标签{% %}

一.变量

1.初识

后端:
a = 10
def test(reuqest):
	return render(request,"test.html",{"a":a}) 

前端:
<p>{{ a }}</p>

后端把a这个变量传递给test.html,只要test.html使用就可以在页面上渲染出来

2.(.) 方法
模板语言中的取值和调用方法和py不太一样,统统都是** .**方法,类似于py中的对象取属性

a = [1,2,3]
取a中第二个元素:{{ a.1 }} #不是py中的a[1]

b = {"name":"alex","age":58}
获取name的值:{{ b.name }}  #不是py中的b.name

 class A:
 	def run(self):
 		pass
 a = A()
 调用a的run方法:{{ a.run }}  #不是py中的a.run()

后端给前端传的既可以是个变量也可是个对象(py中一切皆为对象嘛)

3.注意事项
** . **方法的调用有个优先级:
1.是否为字典中的key
2.对象的属性或方法(如果属性和方法同名,先调用属性)
3.数字索引

拿几个例子看一下:

1.
dic = {"keys":"a"}
{{ dic.keys }}   
这里返回的是a,因为django首先会判断keys是不是字典中的key,结果判断是key,所以返回keys对应的值a,而不是调用dict的keys方法

2.
class A:
	def __init__(self,name):
		self.name = name
	def name(self):
		return "name"
a = A("alex")
{{ a.name }} 
这里a.name结果是alex,因为name属性和name方法重名,由于** . **方法判断机制的存在,所以是alex

4.补充
(1)使用板语言中调用方法不能传参
官方文档:
在这里插入图片描述
ps:咱也不知道为啥,咱也不敢问
(2)使用数字索引取值时不能用-1

二.标签

1.for
(1)简单for

{% for foo in test %}
	{{ foo }}
{% endfor %}

(2)for…emty

test = [[1],[],[2],[],[3]]
{% for a in test %}
	{% for i in a %}
    	{{ a }}
	{% empty %}    如果i为空则走下边
    	<a href="">爪巴</a>   
	{% endfor %}
{% endfor %}

页面结果:在这里插入图片描述
(3)for循环的属性

forloop.counter   	   当前循环的索引(1开始)
forloop.counter0  	   当前循环的索引(0开始)
forloop.revcounter     当前循环的倒序索引(1结束)
forloop.recvcounter0   当前循环的倒序索引(0结束)
forloop.first		   当前循环是不是第一次循环(布尔值)
forloop.last           当前循环是不是最后一次循环(布尔值)
forloop.parloop        返回父循环的一些信息

2.if

    {% for a in test %}
        {% if a|length == 1 %}
            长度为1
        {% elif a|length == 0 %}
            长度为0
        {% else %}
            未知
        {% endif %}
    {% endfor %}

3.with

test = [[1],[],[2],[],[3]]
{% for foo in test %}
	{% if forloop.counter == 1 %}
    	{% with k=foo %}
        	{{ k.0 }}
        {% endwith %}
        {{ k.0 }}
    {% else %}
        {{ k }}
    {% endif %}
{% endfor %}

with提供一个中间变量来暂时存储值,这个变量只能在with逻辑中使用,其他地方都不能用

页面结果:
在这里插入图片描述

4.注意事项
(1)模板语言不支持连续判断

{{ 1<a<5 }}     #模板语言中会报错

在这里插入图片描述
正确写法:

{{ a > 1 and a < 5 }}

(2)运算符前后必须要有空格

{{ a<5 }}

在这里插入图片描述
正确写法:

{{ a < 5 }}

三.补充内容

1.注释
注释的写法:{# … #}

{# 这是注释 #}

2.csrf_token标签
刚学django的时候知道将中间件
django.middleware.csrf.CsrfViewMiddleware注释掉以后就可以提交post请求,用csrf_token标签不用注释中间件达到同样的效果

<form action="" method="post">
{% csrf_token %}
......
</form>

原理以后再深入分析

最后,django模板语言官方文档:
https://docs.djangoproject.com/en/1.11/ref/templates/language/
大家有兴趣可以去看一下

发布了62 篇原创文章 · 获赞 13 · 访问量 2965

猜你喜欢

转载自blog.csdn.net/Yanghongru/article/details/105420405
今日推荐