您的位置:首页 > 编程语言 > Go语言

Django学习--005--模版深入

2016-04-26 00:00 369 查看
本节主要学习Django模板中的循环,条件判断,常用的标签,过滤器的使用。
列表,字典,类的实例的使用
一般的变量之类的用 {{ }}(变量),功能类的,比如循环,条件判断是用 {% %}

循环:迭代显示列表,字典等中的内容

条件判断:判断是否显示该内容,比如判断是手机访问,还是电脑访问,给出不一样的代码。

标签:for,if 这样的功能都是标签。

过滤器:管道符号后面的功能,比如{{ var|length }},求变量长度的 length 就是一个过滤器。

1.将基本字符串显示在网页上

/转义的斜杠/#coding:utf-8

from django.shortcuts import render

def index(request):
str = "插入字符串"
return render(request, 'index.html', {'string': str})

然后在模版文件中使用,在home.html文件中插入下面代码即可:

{{string}}

用一个string变量把字符串传入html页面,使用“{{ }}”让代码可以执行显示。

2.基本的循环(for和list)

/#coding:utf-8
from django.shortcuts import render

/# Create your views here.
def  index(request):
str = '插入字符串'
test_for = ['插','入','字','符','串']
return  render(request, 'index.html',{'string':str,'testfor':test_for})

然后在模版文件中使用,在home.html文件中插入下面代码即可:

<body>
欢迎来到Django的世界
{{string}}
{% for i in testfor%}
{{ i }}
{% endfor %}
</body>


注意:for 循环要有一个结束标记
下面是浏览器返回的网页内容

欢迎来到Dja ngo的世界 插入字符串 教程列表: 插 入 字 符 串

3.显示字典的内容

在view.py中定义函数如下。

def  index(request):
test_item = {'name':'字符串','length':3}
return  render(request, 'index.html',{'testitem':test_item})

然后在模版文件中使用,在home.html文件中插入下面代码即可:

<body>
欢迎来到Django的世界
{{testitem.name}}
{{testitem.length}}
</body>

浏览器返回结果如下:

欢迎来到Django的世界 字符串 3

注意:模板中取字典中的键使用的是testitem.name

遍历字典方法如下:

<body>
欢迎来到Django的世界

{% for key, value in testitem.items %}
{{ key }}: {{ value }}
{% endfor %}
</body>

浏览器返回结果如下

欢迎来到Django的世界 length: 3 name: 字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: