如何在django模板中使用变量作为索引?

jan*_*anb 4 python arrays django indexing templates

如何在django模板中使用变量作为索引?

现在我收到此错误:

Exception Type:
TemplateSyntaxError

Exception Value:    
Could not parse the remainder: '[year]' from 'bikesProfit.[year]'
Run Code Online (Sandbox Code Playgroud)

我也尝试了,{{ bikesProfit.year }}但这给出了一个空洞的结果.

 {%  for year in years_list %}

        <tr>
            <th>Total profit {{ year }}:</th>
        </tr>
        <tr>
            <th></th>
            <th> {{ bikesProfit[year] }} </th>

...
Run Code Online (Sandbox Code Playgroud)

Ser*_*ney 15

这是一个非常普遍的问题,SO上有很多答案.

您可以制作自定义模板过滤器:

@register.filter
def return_item(l, i):
    try:
        return l[i]
    except:
        return None
Run Code Online (Sandbox Code Playgroud)

用法:

{{ bikesProfit|return_item:year }}
Run Code Online (Sandbox Code Playgroud)