在Django模板中打印字典值

时间:2012-08-29 07:56:35

标签: django

我将两个名为student_idsrows的词典传递给Django模板。字典student_ids有一个名为student_idinvite_id的密钥,我想打印student_ids[student_id]以获取invite_id

行词典中第4行的元素与student_id相同。当我尝试下面的代码时,它不起作用......

Django模板:

{% for row in rows %}
    <a href="#invite"
     data-invite="{{ invite_ids.row.4 }}">
     {{ row.2 }}
    </a>
{% endfor %}

如何在Django模板中获取正确的数据?我基本上需要打印student.ids[row[4]],并且要简单......

2 个答案:

答案 0 :(得分:2)

The dictionary student.ids has a key called student_id and invite_id and i would like to print out the student.ids[student_id] to get the invite_id.

试试这个:

{% for sid, iid in student.ids.items %}
    {{ sid }} -- {{ iid }}
{% endfor %}

顺便说一句:由于那个点,你的字典名称很奇怪而且令人困惑。我会把它改成studentIds或者什么......

根据您的修改进行了更新:

首先检查一下:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

我真的不明白你到底是怎么回事,但是如果你想根据一个等于student_id的键从行dict中访问一个值,你可以尝试这个并看看它如何为你工作并将其调整为你的需求:

{% for student_id, student_id_value in student.ids.items %}
     {{ student_id }}
     {{ rows.student_id }}
{% endfor %}

答案 1 :(得分:1)

解决这个问题:

{% for t_id, i_id in teacher_invite_ids.items %}
 {% if t_id == row.4 %}
  {{ i_id }}
 {% endif %}
{% endfor %}
相关问题