将带有网址的数组传递到模板中

时间:2018-07-04 15:12:50

标签: python django

我在这里找到了正确的网址

from django.http import HttpResponse
from django.shortcuts import render
import requests

def main(request):
    return render(request,'main.html')

req = requests.get('https://d3.ru/api/posts').json()
arr = []
for data in req['posts']:
    urls = data['main_image_url']
    if urls != None:
        arr.append(urls)
print('urls',arr)

如何将数组arr传递到模板main.html<img class>

{% extends "wrapper.html" %}
{% block title %}
<div class="container">
    <img class = "col-12 ml-auto col-12 mr-auto" src=///arr???>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

您可以在render ant中将列表作为参数传递,然后在模板中对其进行循环

例如:

Views.py

def main(request):
    req = requests.get('https://d3.ru/api/posts').json()
    arr = []
    for data in req['posts']:
        urls = data['main_image_url']
        if urls != None:
            arr.append(urls)
    print('urls', arr)
    return render(request, 'main.html', {'arr': arr})

和模板

{% extends "wrapper.html" %}
{% block title %}
<div class="container">
    {% for i in arr %}
        <img class = "col-12 ml-auto col-12 mr-auto" src={{ i }}>
    {% endfor %}
</div>
{% endblock %}