【问题标题】:Accessing list item in django template访问 django 模板中的列表项
【发布时间】:2015-05-11 09:20:45
【问题描述】:

我在从视图呈现的模板中有一个列表,rate_text ['', 'Disappointed', 'Not Promissing', 'OK', 'Good', 'Awesome']。我可以使用{{rate_text.index}} 访问其中的任何项目,如下所示:

{% for review in reviews %}
<div class="panel panel-info" style='border-color:#ffffff;'>
    <div class="panel-heading" >
        <h3 class="panel-title lead">{{review.title}}</h3>
    </div>
    <div class="panel-body">
       <p class='text-center'>{{review.review}}</p>
       <h5 class='text-right'>-{{review.username}} ( {{review.email}} ) </h5>
       <h5 class='text-right'>Rating : {{rate_text.4}}</h5>
    </div>
</div>
<hr>
{% endfor %}

但是,我不想在{{rate_text.index}} 中使用索引,而是使用{{review.rating}} 作为索引。有什么办法可以做到这一点?? 提前致谢。

【问题讨论】:

    标签: python django django-templates django-template-filters


    【解决方案1】:

    最好的选择是为rating 字段使用choices 属性:

    RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing',
                                     'OK', 'Good', 'Awesome']))
    
    class Review(models.Model):
        ...
        rating = models.IntegerField(..., choices=RATING_CHOICES)
    

    然后在模板中使用:

    {{ review.get_index_display }}
    

    另一种选择是使用custom template filter:

    @register.filter
    def get_by_index(lst, idx):
        return lst[idx]
    

    模板如下所示:

    {{ rate_text|get_by_index:review.rating }}
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2011-05-03
      • 2012-10-19
      • 2018-01-17
      • 2023-03-20
      • 2010-12-01
      • 2015-08-18
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多