其他分享
首页 > 其他分享> > inclusion_tag 自定义

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

<ul>
  {% for choice in data %}
    <li>{{ choice }}</li>
  {% endfor %}
</ul>

templates/index.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>inclusion_tag test</title>
</head>
<body>

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

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

 

标签:自定义,inclusion,py,html,tag,result,template
来源: https://www.cnblogs.com/hellofeiyu/p/15601036.html