本节主要学习Django模板中的循环,条件判断,经常使用的标签,过滤器的使用。 列表,字典,类的实例的使用 通常的变量之类的用 {{ }}(变量),功能类的,好比循环,条件判断是用 {% %}html
/转义的斜杠/#coding:utf-8
from django.shortcuts import renderdjango
def index(request): str = "插入字符串" return render(request, 'index.html', {'string': str})浏览器
而后在模版文件中使用,在home.html文件中插入下面代码便可:函数
{{string}}
用一个string变量把字符串传入html页面,使用“{{ }}”让代码能够执行显示。学习
/#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的世界 插入字符串 教程列表: 插 入 字 符 串
在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: 字符串