1 有app books(mysite/books)
models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField(blank=True,null=True)
def __unicode__(self):
return self.title
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from books.models import Book
def showbook(request):
return render_to_response('result_snippet.html',)
2 books下建 templatetags(mysite/books/templatetags)
extras.py
from django import template
from books.models import Book
register = template.Library()
@register.inclusion_tag('book_snippet.html') <<<通过修饰器注册inclution tag。
def books_for_title(titlequery):
books = Book.objects.filter(title=titlequery)
return {'books': books}
3 templates(mysite/templates)
book_snippet.html
<ul>
{% for book in books %}
<li>{{book.title}}</li>
{% endfor %}
</ul>
result_snippet.html
{% load extras %}
{% books_for_title 'one day in Beijing' %} <<< 这是inclution tag的使用方法。
4 组织url
from django.conf.urls import patterns, include, url
import books.views
urlpatterns = patterns('',
('^$',my_homepage_view),
('^showbook/$',books.views.showbook),
)
解释:包含标签(inclution tag)的主要思路是当前模板通过使用其他模板显示数据。
通过@register.inclusion_tag(‘book_snippet.html’) 注册包含标签,在def books_for_title中定义数据的获得方式,在’book_snippet.html’中定义显示方式。
使用时,{% books_for_title titlequery %},前者指示需要调用的自定义函数books_for_title,后者为传给books_for_title函数的参数。