0

Запарился на такой мелочи, но не могу понять как вывести именно следующий массив)

Есть такое:

return render(request, 'main.html', {'arrImages': arrImages,'title': arrTitle})

Массив arrImages выводится без проблем. Но как вывести title? Не понимаю где нужно loop-ить.

<div class="container">
{% for images in arrImages %}
<hr>
    <p class="text-justify"> {{ /////????title }}</p>
    <img class = "col-12 ml-auto col-12 mr-auto" src={{ images }}>
{% endfor %}

Куда бы я не поставил, не работает, или это делается одним циклом? Сорри за такие вопросы, но в инете не нашел)

код views.py

def main(request):
    d3 = requests.get('https://d3.ru/api/posts/?sorting=rating&threshold_date=day').json()
    arrImages = []
    arrTitle = []
    arrText = []
    try:
        for data in d3['posts']:
            imagesPath= ('data', 'link','url')
            images = reduce(lambda c, k: c[k] if c is not None and k in c else None, imagesPath, data)
            if images is not None and ".gif" in images and ".gifv" not in images:
                arrImages.append(images)
            imagesPath2= ('data', 'media','url')
            images2 = reduce(lambda c, k: c[k] if c is not None and k in c else None, imagesPath2, data)
            if images2 is not None:
                arrImages.append(images2)
                titlePath= ('data', 'title')
                textPath= ('data', 'text')
                title = reduce(lambda c, k: c[k] if c is not None and k in c else None, titlePath, data)
                text = reduce(lambda c, k: c[k] if c is not None and k in c else None, textPath, data)
                if title is not None:
                    arrTitle.append(title)
                if text is not None:
                    arrText.append(text)

        print('arrImages',arrImages)
        print('title',arrTitle)
        print('text',arrText)
    except BaseException as e:
        print('ecxeptions: ',e)
    return render(request, 'main.html', {'arrImages': arrImages,'title': arrTitle})
7
  • {% for item in title %} - не работает?
    – Basalex
    10 июл 2018 в 7:58
  • не работает, а чего записи разнятся? По аналогии должно же быть {% for title in arrTitle%} вроде?) 10 июл 2018 в 8:07
  • Тогда уж должно быть не for images in arrImages, а {% for i in range(len(arrImages)) %}, а потом в нужных местах {{ arrImages[i] }} и {{ title[i] }}
    – Avernial
    10 июл 2018 в 8:15
  • @Romik romikromik - нет, в качестве названия переменной используется ключ { ..., 'title': arrTitle }, как видишь у тебя ключ - это title, соотвественно итерировать нужно так же по нему
    – Basalex
    10 июл 2018 в 8:33
  • «а чего записи разнятся?» — так вы же сами в коде написали разное 'title': arrTitle
    – andreymal
    10 июл 2018 в 8:33

1 ответ 1

0

Вот как это выглядит :

return render(request, 'main.html', {'imageTitles': zip(arrImages, arrTitle)})

Затем:

<div class="container">
    {% for image, title in imageTitles %}
    <hr>
        <p class="text-justify">{{ title }}</p>
        <img class = "col-12 ml-auto col-12 mr-auto" src={{ image}}>
    {% endfor %} 

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.