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


   

    `title`

{% if user %}

   

  • name:`user`.`name`
  • {% else %}

    用户不存在

    {% endif %}


    {% for book in book_list %}

       

  • `book`
  • {% endfor %}


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

       

  • `forloop`.`counter`.`k`:`v`
  • {% endfor %}