【问题标题】:Can I access an elements index within a dictionary value?我可以访问字典值中的元素索引吗?
【发布时间】:2021-05-25 20:15:41
【问题描述】:

我正在传递带有一个键值对的字典,其中值是图像列表。有没有办法只遍历值列表中的前 4 个元素?

这是我的views.py文件:

def portfolio_couples(request):
    img_list = os.listdir("/Users/andershanson/Documents/Django/kh_photo/static/my_app/images/portfolio")
    context = {"images": img_list}
    return render(request, 'my_app/couples.html', context)

这是我的 HTML 模板:

{% if images %}
    {% for image in images %}
        <img src="/static/my_app/images/portfolio/{{ image }}" class="container-fluid px-0 m-0" alt="portfolio-pic">
    {% endfor %}
{% endif %}

目前可以循环遍历图像,但是有没有办法索引字典值中的前 4 个元素?谢谢!

【问题讨论】:

    标签: python django dictionary templatetags


    【解决方案1】:

    您可以在视图中对其进行切片:

    def portfolio_couples(request):
        img_list = os.listdir("/Users/andershanson/Documents/Django/kh_photo/static/my_app/images/portfolio")
        #                    slicing &downarrow;  &downarrow;
        context = {"images": img_list[:4]}
        return render(request, 'my_app/couples.html', context)

    |slice template filter [Django-doc]:

    {% for image in images|slice:":4" %}
        <img src="/static/my_app/images/portfolio/{{ image }}" class="container-fluid px-0 m-0" alt="portfolio-pic">
    {% endfor %}

    但视图可能是执行此操作的最佳位置,因为视图负责业务逻辑,而模板负责渲染逻辑。

    【讨论】:

    • 非常感谢!有什么办法可以在模板标签中做到这一点??
    • @ahanson:是的,虽然我不建议在模板中这样做。
    • 谢谢!欣赏你的智慧
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2011-04-28
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多