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

本节主要学习Django模板中的循环,条件判断,经常使用的标签,过滤器的使用。 列表,字典,类的实例的使用 通常的变量之类的用 {{ }}(变量),功能类的,好比循环,条件判断是用 {% %}html

  • 循环:迭代显示列表,字典等中的内容
  • 条件判断:判断是否显示该内容,好比判断是手机访问,仍是电脑访问,给出不同的代码。
  • 标签:for,if 这样的功能都是标签。
  • 过滤器:管道符号后面的功能,好比{{ var|length }},求变量长度的 length 就是一个过滤器。

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

/转义的斜杠/#coding:utf-8
from django.shortcuts import renderdjango

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文件中插入下面代码便可:code

<body>
欢迎来到Django的世界
{{string}}

{% for i in testfor%}
{{ i }}
{% endfor %}
</body>

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

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

3.显示字典的内容

在view.py中定义函数以下。教程

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

而后在模版文件中使用,在home.html文件中插入下面代码便可:utf-8

<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: 字符串
相关文章
相关标签/搜索