如何在Django框架中使用Jinja?

时间:2019-06-04 06:04:49

标签: django jinja2

我想使用Jinja访问列表的元素。

下面的代码中都列出了“ id”和图像。 image_name是存储图像的字段

   {% for blog in id%}    
        <h3>{{blog.news_title}}</h3><br/>     
        <a href="/blog/article/{{blog.slug}}"><img src="images[loop.index0].image_name"/></a><br/>
        <time>{{blog.news_date}}</time><br/>
        <a href="/blog/article/{{blog.slug}}">click here</a><br/>
    {% endfor%}</li>

Views.py

def BlogViews(request,blog_type):
    """
        The blogs are displayed according to the latest, current-month and last-month classification
    """
    blog_type=blog_type.replace('-','_')
    response_blog=requests.get("API" % (settings.BASE_URL,blog_type),headers=headers,verify=False)
    if(response_blog.status_code==200):
        data_blog=response_blog.json()
        if(data_blog['ErrorCode']==0 and data_blog['SubErrorCode']==0):
            blog=BlogYearViews()
            blog_images=BlogImages(request,data_blog)
            return render(request,"CombinedBlog.html",{"id":data_blog['Data'],"years":blog,"images":blog_images})
        else:
            return render(request,"Page404.html")
def BlogImages(request,data_blog):
    """
        Returns a list of all the images
    """
    data_image_list=[]
    for i in range(0,len(data_blog['Data'])):
        images=data_blog['Data'][i]['image_id']
        response_image=requests.get("API"%(settings.BASE_URL),headers=headers,verify=False)
        data_image=(response_image.json())
        data_image_list=data_image_list+data_image['Data']
    return (data_image_list)

2 个答案:

答案 0 :(得分:0)

要使用索引访问images列表,可以使用 forloop.counter

您可以使用:

{{ forloop.counter }}  # index starts at 1
{{ forloop.counter0 }} # index starts at 0.
  

在模板中,您可以执行以下操作:

<img src="{{images[forloop.counter0].image_name.url}}"/>

建议:

  • 您应该考虑将博客列表重命名为blogsblog_listid

答案 1 :(得分:0)

您需要在视图中将两个列表压缩在一起,并在模板中对其进行遍历。

blog_images = BlogImages(request, data_blog)
blogs_and_images = zip(data_blog['Data'], blog_images)
return render(request, "CombinedBlog.html", {"blogs_and_images": blogs_and_images, "years":blog})

...

{% for blog, image in blogs_and_images %}    
    <h3>{{ blog.news_title }}</h3><br/>     
    <a href="/blog/article/{{ blog.slug }}"><img src="{{ image.image_name }}"/></a><br/>
    <time>{{ blog.news_date }}</time><br/>
    <a href="/blog/article/{{ blog.slug }}">click here</a><br/>
{% endfor %}</li>

请注意,您确实应该使用{% url %}标签来创建href,而不是像这样手动构建它。还要注意,您的BlogImages函数不需要接受请求,因为它从不使用它,并且无论如何都是非Pythonic的。它应该看起来像这样:

def blog_images(data_blog):
    data_image_list = []
    for blog in data_blog['Data']:
        image_id = blog['image_id']
        response_image = requests.get("API" % settings.BASE_URL, headers=headers, verify=False)
        data_image = response_image.json()
        data_image_list.append(data_image['Data'])
    return 

data_image_list