【问题标题】:How to iterate over a list in django template如何遍历 django 模板中的列表
【发布时间】:2020-10-14 14:29:27
【问题描述】:

我想遍历一个在元组模板中传递的列表。我想在它们的相对位置显示一些描述。我有一个列表中的所有描述(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}} 位置显示相关描述,但它是一个完整列表。

【问题讨论】:

    标签: python django


    【解决方案1】:

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

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

    &lt;p class="truncate"&gt;{{ post.3 }}&lt;/p&gt; 行替换为上面的行。

    您可以阅读此Section of the Official Django Documentation 以了解模板标签的工作原理。 Similar Question 也可以帮助您了解它的工作原理。

    【讨论】:

    • 我已经尝试过你的建议,但它在每张卡上显示所有描述(7-8),而不是一个。
    • 您想要一张卡片上的所有描述还是所有卡片上的所有描述?
    • 或者它只是你想要在所有卡片上的一个描述?
    • 我想要一张卡片上分别有一个描述。
    【解决方案2】:

    我创建了自己的模板标签并在模板中使用它,并且为了在一篇文章中迭代一个项目,我使用了 Django 的默认 for loop variables

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 2010-10-21
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2020-04-04
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多