Python Django模板标签

一、if、for标签


# cat blog/views.py

from django.shortcuts import render_to_response


def index(req):

    user = {'name':'loyu','age':23,'sex':'male'}

    book_list = ['python','java','php','web']

    return render_to_response('index.html',{'title':'Loyu page','user':user,'book_list':book_list})



# cat blog/template/index.html


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title>`title`</title>

</head>

<body>

{% if user %}

   <li>name:`user`.`name`</li>

{% else %}

用户不存在

{% endif %}


{% for book in book_list %}

   <li>`book`</li>

{% endfor %}


{% for k,v in user.items %}

   <li>`forloop`.`counter`.`k`:`v`</li>

{% endfor %}

</body>

</html>