且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django-使用模板中的变量调用列表或字典项

更新时间:2023-11-25 22:30:46

Django模板语言不允许您访问字典键和带有变量的列表.您可以编写一个模板标签来执行此操作(例如,参见此问题),但是在您的情况下,有一个更简单的选择. /p>

在您看来,将表格和标题压缩在一起

tables_and_titles = zip(tables, tabletiles)

然后在模板中一起遍历它们.

{% for table, title in tables_and_titles %}
    {{ title }}
    <table>
    {{ table }}
    </table>
{% endfor %}

I'm trying to call a dictionary or list object in a template using a variable in that template with no results.

What I'm trying to is identical to this general python code:

keylist=[
        'firstkey',
        'secondkey',
        'thirdkey',
        ]
exampledict={'firstkey':'firstval',
             'secondkey':'secondval',
             'thirdkey':'thirdval',
             }

for key in keylist:
    print(exampledict[key])

#Produces:
    #firstval
    #secondval
    #thirdval

Things work a little different in the django template. I have a variable defined as key='firstkey' passed onto the template. If i want to call the same dictionary:

{{ exampledict.firstkey }} #Produces: firstval
{{ exampledict.key }} #Produces: None

Django template for loops also has a produced variable forloop.counter0, increasing from 0 in the firstloop to n-1 in the last loop, this cannot call list objects. I have a list:

tabletitles=['first table', 'second table', 'third table']

And I want to call and create tables in a loop, putting the table titles for the respective tables above like so:

{% for table in tables %}
<h3> first table </h3>
<table>
...
</table>
{% endfor %}

What I would like to do in this case is

{% for table in tables %}
<h3> {{ tabletitles.forloop.counter0 }} </h3>
<table>
...
</table>
{% endfor %}

Which doesn't work either, since I can't use a separate variable to call an object for a dict or list in the template. Is there a way to get this to work, or a better way to do it all together?

The Django template language does not let you access dictionary keys and lists with variables. You could write a template tag to do this (see this question for example), but in your case there's a simpler alternative.

In your view, zip your tables and titles together

tables_and_titles = zip(tables, tabletiles)

Then loop through them together in your template.

{% for table, title in tables_and_titles %}
    {{ title }}
    <table>
    {{ table }}
    </table>
{% endfor %}