包含模板标签,它返回使用次数,并且在使用模板继承时不会中断。我尝试在上下文中存储计数器,但它不能像我预期的那样工作。
base.html文件
{% block body %}
{% my_tag %}<br>
{% my_tag %}<br>
{% endblock %}
page.html中
{% extends 'base.html' %}
{% block body %}
{{ block super }}
{% my_tag %}<br>
{% my_tag %}<br>
{% endblock %}
渲染结果:
1
2
3
4
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
counter = context.get('tag_counter', 1)
ctx = {'tag_counter': counter}
context['tag_counter'] = counter + 1
return ctx
结果:
1
2
1
2
添加了向请求添加计数器的中间件
class TagCounterMiddleware(object):
def process_request(self, request):
request.tag_counter = 1
并更改了模板标记
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
request = context.get['request']
ctx = {'tag_counter': request.tag_counter}
request.tag_counter += 1
return ctx
感谢@SardorbekImomaliev提出的建议! :)
答案 0 :(得分:1)
我建议你把你的柜台放在request
。这样的事情。
# This code wasn't checked
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
request = context.get('request')
counter = getattr(request, 'tag_counter', 0)
request.tag_counter = counter + 1
context['request'] = request
return context