Django 未在多模板渲染()上重置周期
我制作了一个标记,用于根据模型类型呈现自定义模板。我之所以需要它,是因为我想显示比Django 未在多模板渲染()上重置周期,django,django-templates,Django,Django Templates,我制作了一个标记,用于根据模型类型呈现自定义模板。我之所以需要它,是因为我想显示比django.views.generic.list\u detail.object\u list更详细的内容。让我为单个对象显示,我有多个不同类型的对象。代码如下: 模板tags/extra.py: from django import template register = template.Library() def render_item_list(parser, token): try:
django.views.generic.list\u detail.object\u list更详细的内容。让我为单个对象显示,我有多个不同类型的对象。代码如下:
模板tags/extra.py:
from django import template
register = template.Library()
def render_item_list(parser, token):
try:
tag_name, item_list = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires exactly one arguments" % token.split_contents()[0]
return RenderItemListNode(item_list)
class RenderItemListNode(template.Node):
def __init__(self, item_list):
self.item_list = template.Variable(item_list)
def render(self, context):
list_html = ''
for item in self.item_list.resolve(context):
context.update({'item':item})
list_html += template.loader.get_template("list/%s_item.html" % item.__class__.__name__.lower()).render(context)
return list_html
register.tag('render_item_list', render_item_list)
我的问题是模板使用了{{cycle}},并且每次调用render()
都会重置值
我可能会将周期值添加到我自己的标记中,但我想看看是否有更好的解决方案,比如不跨render()
调用重置周期值,或者甚至不使用与我的标记不同的方法
更多代码:
index.html
:
{% extends "base.html" %}
{% load extra %}
{% block content %}
{% render_item_list item_list %}
{% endblock %}
object\u item.html
代码段:
<div class="{{ cycle 'odd' 'even' }}" >
...
</div>
发生这种情况的原因是,cycle标记在for循环中工作——在模板中,没有for循环,因此循环没有更新
如果要按原样使用循环,可以尝试在模板中呈现整个对象列表,然后让模板在其上执行for循环,而不是在代码中执行循环。将object\u item.html更改为如下所示:
{% for item in item_list %}
<div class="{{ cycle 'odd' 'even' }}" >
...
</div>
{% endfor %}
我尝试了一种不同的方法,这样我就可以在for循环中使用我的标记,但不起作用。正如您所说,我将标记移出了我的object_item.html,并且我使用了第二种形式的代码,如我所示。真不敢相信我自己没想到,谢谢。
{% for item in item_list %}
<div class="{{ cycle 'odd' 'even' }}" >
...
</div>
{% endfor %}
def render(self, context):
item_list = self.item_list.resolve(context)
list_html = template.loader.get_template("list/%s_item.html" % item.__class__.__name__.lower()).render({'item_list':item_list})
return list_html