在 Django 中,如何迭代需要参数的自定义模板标记的结果?

发布于 2024-07-14 22:50:32 字数 381 浏览 7 评论 0原文

如果我创建了模板标签:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月静好 2024-07-21 22:50:33
{% last_books sports 3 as last_books %}  # do it like this

{% for book in last_books 'Sports' 3 %}
       ...
{% endfor %}

但最好使用 Include_tag

{% last_books sports 3 as last_books %}  # do it like this

{% for book in last_books 'Sports' 3 %}
       ...
{% endfor %}

but it's better to use inclusion_tag

执笔绘流年 2024-07-21 22:50:32

就我个人而言,我只是通过视图将书作为上下文变量传递。 这样您就不需要模板标签。

或者,您可以使用 Include_tag 装饰器,它将使用自定义上下文呈现包含模板到当前文档中的想法。

但如果您想继续当前路径,则 simple_tag 装饰器不是正确的选择。 当您需要返回想要直接呈现到模板中的字符串时,可以使用它。 您想要做的是设置模板上下文变量。 这有点复杂,但不太困难。 创建一个像这样的节点:

class LastBooksNode(template.Node):
    def __init__(self, category, cutoff=5, var_name='books'):
        self.category = category
        self.cutoff = cutoff
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = Books.objects.filter(category=self.category)[:self.cutoff]
        return ''

@register.tag(name='last_books')
def do_last_books(parser, token):
    error = False
    try:
        tag_name, category, cutoff, _as, var_name = token.split_contents()
        if _as != 'as':
            error = True
    except:
        error = True

    if error:
        raise TemplateSyntaxError, 'last_books must be of the form, "last_books <category> <cutoff> as <var_name>"'
    else:
        return LastBooksNode(a_cat, cutoff, var_name)

然后您将使用以下内容调用模板标记:

{% import <your tag library> %}
{% last_books 'category' 5 as my_books %}
{% for book in my_books %}
    ....
{% endfor %}

未经测试,但我希望这演示了这个想法。 不过,如上所述,如果您不打算在多个地方重用它,那么通过上下文将书籍直接传递到视图或使用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 a string 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:

class LastBooksNode(template.Node):
    def __init__(self, category, cutoff=5, var_name='books'):
        self.category = category
        self.cutoff = cutoff
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = Books.objects.filter(category=self.category)[:self.cutoff]
        return ''

@register.tag(name='last_books')
def do_last_books(parser, token):
    error = False
    try:
        tag_name, category, cutoff, _as, var_name = token.split_contents()
        if _as != 'as':
            error = True
    except:
        error = True

    if error:
        raise TemplateSyntaxError, 'last_books must be of the form, "last_books <category> <cutoff> as <var_name>"'
    else:
        return LastBooksNode(a_cat, cutoff, var_name)

You would then invoke the template tag with:

{% import <your tag library> %}
{% last_books 'category' 5 as my_books %}
{% for book in my_books %}
    ....
{% endfor %}

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.

梦屿孤独相伴 2024-07-21 22:50:32

为什么不with

Why not with?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文