繁体   English   中英

如何遍历 django 模板中的列表

[英]How to iterate over a list in django template

我想遍历在元组中通过模板传递的列表。 我想在它们的相对位置显示一些描述。 我有一个列表中的所有描述(7-8)。 这是 views.py 文件的样子:

from django.shortcuts import render

import requests
from bs4 import BeautifulSoup
from .functions import get_descriptions


def index(request):

    url = requests.get('https://thehackernews.com/')
    soup = BeautifulSoup(url.content, 'html.parser')

    post_container = soup.find(class_='blog-posts')
    post_body = post_container.find_all(class_='body-post')
    total_news = range(0, len(post_body))

    descs = get_descriptions(post_body=post_body) # a list of descriptions

    final_postings = []
    for link in post_body:
        post_link = link.find(class_='story-link').attrs
        lnk_lst = str(post_link['href'])
        # print(lst)

        images = link.find(class_='home-img-src').attrs
        src_lst = str(images['data-src'])
        # print(src_lst)

        titles = link.find(class_='home-title').get_text()

        post_dates = link.find(class_='item-label').get_text()

        final_postings.append((lnk_lst, src_lst, titles, descs))

    front_end_stuff = {'final_postings': final_postings, 'news': total_news}
    return render(request, 'mainapp/index.html', context=front_end_stuff)

模板 mainapp/index.html 看起来像:

{% extends 'mainapp/main.html' %}

{% block content %}

{% for post in final_postings %}
<div class="card hoverable">
    <div class="card-content">
        <div class="row">
            <div class="col s12 l4">
                <div class="card-image">
                    <img src="{{ post.1 }}" alt="news" class="responsive-img">
                </div>
            </div>
            <div class="col s12 l7 offset-l1">
                <a href="{{ post.0 }}" class="black-text"><div class="title">{{ post.2 }}</div></a>
                <p class="truncate">{{ post.3 }}</p>
            </div>
        </div>
    </div>
</div>
{% endfor %}

{% endblock content %}

我想显示每张卡片中 {{post.3}} 位置的相关描述,但它是一个完整列表。

鉴于您已经声明{{post.3}}呈现完整列表,您可以通过遍历列表来访问单个项目。

{% for item in post.3 %}
    <p class="truncate">{{ item }}</p>
{% endfor %}

用上面的行替换<p class="truncate">{{ post.3 }}</p>行。

你可以阅读官方 Django 文档的这一来了解模板标签是如何工作的。 一个类似的问题也可以帮助您了解它是如何工作的。

我创建了自己的模板标签并在模板中使用它,为了在一篇文章中迭代一个项目,我使用了 Django 的默认循环变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM