Django之定义标签和过滤器

Django之定义标签和过滤器:

详解django中自定义标签和过滤器

from:http://www.jb51.net/article/117719.htm

 

DJANGO的TAG分为三类:

  • simple_tag : Processes the data and returns a string
  • inclusion_tag : Processes the data and returns a rendered template
  • assignment_tag : Processes the data and sets a variable in the context

1、simple_tag :

 

2、inclusion_tag 

# -*- coding: utf-8 -*-
__author__ = 'ShengLeQi'

from django.template import Library

register = Library()
from  app01 import models

@register.inclusion_tag('inclusion.html')
def inclusion_book(request):
    book_list=models.Book.objects.all()
    print(book_list)

    return {'book_list': book_list}
tag.py
{% for i in book_list %}
    <h2> {{ i.name }}</h2>
{% endfor %}
inclusion.html
{% load tag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   {% inclusion_book request %}
</body>
</html>
sheng.html

 注意:在返回的sheng.html中使用模板标签的时候,需要 导入{% tag %}  tag是这个py的文件名。在引用的地方使用 {% inclusion_book request %}:inclusion_book 是行数名,request 是inclusion_book 的参数。

 

 

 

3、assignment_tag 

 

posted @ 2018-01-31 15:59  ShengLeQi  阅读(159)  评论(0)    收藏  举报