【问题标题】:How to use the current index to get the value of another array?如何使用当前索引获取另一个数组的值?
【发布时间】:2016-04-14 07:48:43
【问题描述】:

我读过this,我有一个这样的数组:

context[u'erreurs'] = {
    'aa': {'titres': [], 'liste': [], 'urls': []},
    'bb': {'titres': [], 'liste': [], 'urls': []},
    '...': {'titres': [], 'liste': [], 'urls': []}
}

如果出现错误,'titres''liste''urls' 将变为字符串数组,填充适当的值。

在我的模板中,如果设置了 erreur,我会这样做:

    {% for idx, tab in erreurs.items %}
        <ul>
        {% for e in tab.liste %}
            {% if user.is_authenticated %}
            <li><a href="{{ tab.urls[forloop.counter0] }}">{{ e }}</a></li>
            {% else %}
            <li>{{ e }}</li>
            {% endif %}
        {% endfor %}
        </ul>
    {% endfor %}

我想使用当前索引来使用另一个数组中的值,这里是:tab.urls。它不起作用并给我错误:

Could not parse the remainder: '[forloop.counter0]' from 'tab.urls[forloop.counter0]'

如何解决?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    不幸的是,Django 的模板不支持这种语法。您应该组合一个自定义模板过滤器:

    # yourapp/templatetags/yourapp_tags.py:
    from django import template
    register = template.Library()
    
    @register.filter
    def at_index(array, index):
        return array[index]
    

    并像这样使用它:

    {% load yourapp_tags %}
    {{ tab.urls|at_index:forloop.counter0 }}
    

    【讨论】:

    • 好的,但我要求解决方法,或者建议如何做到这一点?非常感谢
    【解决方案2】:

    您需要制作一个代表数据的实际模型,然后任务就变得微不足道了

    class YourModel(object):
        titre = ''
        liste = '' 
        url = ''
    
    context[u'erreurs'] = {
        'aa': [],  # List of model
    }
    
    {% for idx, tab in erreurs.items %}
        <ul>
        {% for model in tab %}
            {{ model.titre }}
            {{ model.liste }}
            {{ model.url }}
        {% endfor %}
        </ul>
    {% endfor %}
    

    【讨论】:

    • 感谢您的回答,但titrelisteurl 是数组,所以我不能这样处理。
    • @OlivierPons - 当然可以,这只是在分配给上下文之前将三个数组转换为一个对象数组的预处理步骤
    猜你喜欢
    • 2020-09-28
    • 2018-03-28
    • 2018-03-03
    • 2021-11-24
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多