在 Django 中,如何迭代需要参数的自定义模板标记的结果?
如果我创建了模板标签:
@register.simple_tag
def last_books(a_cat, cutoff=5):
objects = Books.objects.filter(category=a_cat)
return objects[:cutoff]
我如何在模板中执行类似的操作:
{% for book in last_books 'Sports' 3 %}
我当前收到此错误:
“for”语句应使用“for x in y”格式:for x in last_books 'Sports' 3
If I have created a template tag:
@register.simple_tag
def last_books(a_cat, cutoff=5):
objects = Books.objects.filter(category=a_cat)
return objects[:cutoff]
How can I do something like this in my template:
{% for book in last_books 'Sports' 3 %}
I am currently getting this error:
'for' statements should use the format 'for x in y': for x in last_books 'Sports' 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
但最好使用 Include_tag
but it's better to use inclusion_tag
就我个人而言,我只是通过视图将书作为上下文变量传递。 这样您就不需要模板标签。
或者,您可以使用 Include_tag 装饰器,它将使用自定义上下文呈现包含模板到当前文档中的想法。
但如果您想继续当前路径,则
simple_tag
装饰器不是正确的选择。 当您需要返回想要直接呈现到模板中的字符串
时,可以使用它。 您想要做的是设置模板上下文变量。 这有点复杂,但不太困难。 创建一个像这样的节点:然后您将使用以下内容调用模板标记:
未经测试,但我希望这演示了这个想法。 不过,如上所述,如果您不打算在多个地方重用它,那么通过上下文将书籍直接传递到视图或使用clusion_tag可能会更容易。
Personally, I would simply pass in the book as a context variable via the view. That way you have no need for a template tag.
Alternately, you could use the inclusion_tag decorator instead, which wraps up the idea of rendering an include template with a custom context into the current document.
But if you want to continue on the current path, the
simple_tag
decorator isn't the way to go. It's for use when you need to return astring
which you want rendered directly into the template. What you're trying to do is set a template context variable. This is a bit more involved, but not too difficult. Create a node something like this:You would then invoke the template tag with:
Untested, but I hope this demonstrates the idea. As mentioned above, though, passing the books directly to the view via the context or using an inclusion_tag may be easier if you don't intend to reuse this in multiple places.
为什么不with?
Why not with?