inclusion_tag 自定义


inclusion_tag

多用于返回html代码片段

1. 在应用下建立 templatetags 文件夹

2. 在文件夹下建立任意名字的py文件

3.固定导入模块

from django import template

register = template.Library()

4. 书写代码

@register.inclusion_tag('result.html') #result.html 为小页面的前端代码块

return locals()返回全部数据

5. result.html 按正常的使用就行,{{取值}}

6. 调用方式

{% load inclusion_tag_test %} #文件名字 不带.py 由于是固定的文件夹,所有不用带路径

{% show_results 10 %} #函数名字 可以带参数 可以带多个参数,只能是位置参数不能写名字 

示例:

templatetags/my_inclusion.py

from django import template

register = template.Library()


@register.inclusion_tag('result.html')
def show_results(n):
    n = 1 if n < 1 else int(n)
    data = ["第{}项".format(i) for i in range(1, n+1)]
    return {"data": data}#或者使用 return locals()返回全部数据

templates/snippets/result.html

    {% for choice in data %}
  • {{ choice }}
  • {% endfor %}

templates/index.html




  
  
  
  inclusion_tag test



{% load inclusion_tag_test %} #文件名字 不带.py

{% show_results 10 %} #函数名字 可以带参数 可以带多个参数,只能是位置参数不能写名字