[Answered ]-Can I access an elements index within a dictionary value?

1👍

You can slice this in the view:

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

or with the |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 %}

But likely the view is the best place to do this, since the view is responsible for the business logic, whereas a template is responsible for the rendering logic.

Leave a comment