我如何使用一个变量作为Django模板指数? [英] How can I use a variable as index in django template?

查看:101
本文介绍了我如何使用一个变量作为Django模板指数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用一个变量作为指数Django模板?

现在我得到这个错误:

 异常类型:
TemplateSyntaxError例外的值:
从【同期】:无法解析,其余'bikesProfit [年]。

我也试过 {{} bikesProfit.year} 但是这给一个空的结果。

  {%的年years_list%}        &所述; TR>
            百分位个总利润{{一年}}:LT; /第i
        < / TR>
        &所述; TR>
            百分位>< /第i
            <第i个{{bikesProfit [年份]}}< /第i...


解决方案

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

您可以<一个href=\"https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters\"相对=nofollow>自定义模板过滤:

  @ register.filter
高清return_item(L,I):
    尝试:
        RETURN L [I]
    除:
        返回None

用法:

  {{bikesProfit | return_item:一年}}

How can I use a variable as index in django template?

Right now I get this error:

Exception Type:
TemplateSyntaxError

Exception Value:    
Could not parse the remainder: '[year]' from 'bikesProfit.[year]'

I also tried {{ bikesProfit.year }} but this gives an empty result.

 {%  for year in years_list %}

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

...

解决方案

It's a very common question, there are a lot of answers on SO.

You can make custom template filter:

@register.filter
def return_item(l, i):
    try:
        return l[i]
    except:
        return None

Usage:

{{ bikesProfit|return_item:year }}

这篇关于我如何使用一个变量作为Django模板指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆