简体   繁体   English

Django-创建自定义标签以按模板中的索引访问变量

[英]Django - create custom tag to acces variable by index in template

I have a HTML template in django. 我在Django中有一个HTML模板。 It get's two variables: list of categories (queryset, as it it returned by .objects.all() function on model in django) and dictionary of contestants. 它有两个变量:类别列表(查询集,由Django模型上的.objects.all()函数返回.objects.all() As a key of the dictionary, I'm using id of category, and value is list of contestats. 作为字典的键,我使用的是类别ID,其值是比赛清单。 I want to print name of the category and then all the contestants. 我想先打印类别名称,然后再打印所有参赛者。 Now I have this: 现在我有这个:

{% for category in categories_list %}
    <h1>category.category_name</h1>
    {% for contestant in contestants_dict[category.id] %}
        {{ contestant }} </br>
    {% endfor %}
{% endfor %}

However, when I run it, I get error: 但是,当我运行它时,出现错误:

TemplateSyntaxError at /olympiada/contestants/
Could not parse the remainder: '[category.id]' from 'contestants_dict[category.id]'

What I know so far is that I can't use index in template. 到目前为止,我所知道的是我无法在模板中使用索引。 I thought that {% something %} contains pure Python, but it shoved up it's just a tag. 我以为{% something %}包含纯Python,但是它只是一个标签而已。 I know that I have to create my own simple_tag, but I don't know how. 我知道我必须创建自己的simple_tag,但我不知道如何。 I read the docs Writing custom template tags , but there is such a little information and I wasn't able to fiqure out how to create (and mainly use in a for loop) a tag, that will take dict, key and return the value. 我阅读了文档“ 编写自定义模板标签” ,但是了解的信息很少,我无法确定如何创建(主要是在for循环中使用)标签,该标签将采用dict,key并返回值。 What I tried is: templatetags/custom_tags.py: 我试过的是:templatetags / custom_tags.py:

from django import template


register = template.Library()


@register.simple_tag
def list_index(a, b):
    return a[b]

and in template: 并在模板中:

{% for contestant in list_index contestants_dict category.id %}

But I get TemplateSyntaxError. 但是我收到了TemplateSyntaxError。 Could you please explain/show me how to create the tag, or is there a better way to do this? 您能否解释一下/向我展示如何创建标签,或者有​​更好的方法吗? Thanks. 谢谢。

//EDIT: I managed to do it this way: //编辑:我设法这样做:

{% list_index contestants_list category.id as cont %}
    {% for contestant in  cont %}

it works, but it takes 2 lines and I need to create another variable. 它可以工作,但是需要2行,我需要创建另一个变量。 Is there any way to do it without it? 没有它,有什么办法吗?

If you don't want 2 lines like that you should be able to use a filter i think 如果您不希望这样的两行,我应该可以使用过滤器

@register.filter
def list_index(a, b):
    return a[b]

Then the usage like this 然后这样的用法

{% for contestant in contestants_dict|list_index:category.id %}
    {{ contestant }} </br>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM