inclusion_tag的使用

# 可以生成一片模板中的代码块
# 使用:5步
-第一步:在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag
-第二步:在app中创建templatetags包(包名只能是templatetags,不能改)
-第三步:在包内,新建py文件(如:my_tags.py)

复制代码
from django import template

register=tmplate.Library()

@register.inclusion_tag('模板名字')#模板也是html片段,可以使用返回的字典,渲染模板

def xx():

  return {key:value}
复制代码

 

-第四步:写代码(inclusion_tag)(第三步的示例)
# inclusion_tag,传一个模板文件
@register.inclusion_tag('left.html')
def left(num):
# dic={0:第0页,1:第1页,2:第2页}
dic = {i: '第%s页' % i for i in range(num)}
# 固定返回的必须是字典
print(dic)
return {'data': dic}

@register.inclusion_tag('beautiful.html')
def beautiful(title, url):
return {'title': title, 'url': url}
-第五步使用:(模板),先load,再使用
{% load my_tags %}
{% left 5%}
{% beautiful '名字' '地址'%}


# 它跟tag有什么不同?
-tag需要再代码中写html的东西
-inclusion_tag代码跟模板分离

posted @   朱饱饱  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示