访问django模板中的列表项

时间:2023-01-10 20:21:56

I have a list, rate_text ['', 'Disappointed', 'Not Promissing', 'OK', 'Good', 'Awesome'] in the template rendered from the view. I can access any of the item of that using {{rate_text.index}} like the following:

我在视图中呈现的模板中有一个列表,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 %}

But, in stead of using index in {{rate_text.index}} I would like to use {{review.rating}} as index. Is there any way that this can be done ?? Thanks in advance.

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

1 个解决方案

#1


1  

The best option is to use choices attribute for the rating field:

最佳选择是为评级字段使用choices属性:

RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing',
                                 'OK', 'Good', 'Awesome']))

class Review(models.Model):
    ...
    rating = models.IntegerField(..., choices=RATING_CHOICES)

And then use it in the template:

然后在模板中使用它:

{{ review.get_index_display }}

The other option is to use custom template filter:

另一种选择是使用自定义模板过滤器:

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

Template will look like this:

模板将如下所示:

{{ rate_text|get_by_index:review.rating }}

#1


1  

The best option is to use choices attribute for the rating field:

最佳选择是为评级字段使用choices属性:

RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing',
                                 'OK', 'Good', 'Awesome']))

class Review(models.Model):
    ...
    rating = models.IntegerField(..., choices=RATING_CHOICES)

And then use it in the template:

然后在模板中使用它:

{{ review.get_index_display }}

The other option is to use custom template filter:

另一种选择是使用自定义模板过滤器:

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

Template will look like this:

模板将如下所示:

{{ rate_text|get_by_index:review.rating }}