本文介绍了jinja2嵌套for循环两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码无法呈现我想要的html前端上的代码.

I have the following code that is not rendering the way I would like on the html front end.

{% for image in images %}
    {% for title in titles %}
        <div class="card" style="width: 18rem;">
          <img src="{{image}}" class="card-img-top" alt="...">
          <div class="card-body">

            <h5 class="card-title">{{title}}</h5>
            <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>


</div>
    {% endfor %}
{% endfor %}

本质上,图像和标题都是URL的列表.单独使用这些图像来重新着色所有图像的HTML时,这些图像可以正常工作.

Essentially, images and titles are both lists of URLS. The images works correctly when on it's own to redner the HTML with all the images.

但是,当我尝试添加标题时,基本上是将图像URL切成仅提供部分URL文本的图像,采用上述格式时,它弄乱了格式,仅显示一张图像.

However, when I try to add titles, which is basically the image URL sliced to give only part of the URL text, in the above format, it messes up the formatting, displaying only one image.

我尝试了各种不同的方法,但是没有用.

I have tried various different ways but it doesn't work.

我希望代码显示卡片中的所有图像,并在TITLE字段中显示相应的标题,在这种情况下,标题是切片的字符串(或者我认为)

I want the code to display all the images in the cards, and in the TITLE field, display the corresponding title, and title in this case is the sliced string (or so I think)

Python(Flask)路线,用于刮擦图像URL和切片代码的功能,如下所示:

@app.route('/') #this is what we type into our browser to go to pages. we create these using routes
@app.route('/home')
def home():
    images=imagescrape()
    titles=(images[58:])
    #gettitles=gettitle()
    #titles=(gettitles[58:93])
    return render_template('home.html',images=images,titles=titles)


def imagescrape():
    result_images=[]
    #html = urlopen('https://en.wikipedia.org/wiki/Prince_Harry,_Duke_of_Sussex')
    html = urlopen('https://en.wikipedia.org/wiki/Rembrandt')
    bs = BeautifulSoup(html, 'html.parser')
    images = bs.find_all('img', {'src':re.compile('.jpg')})
    for image in images:
        result_images.append("https:"+image['src']+'\n') #concatenation!
    return result_images

更新:

我已经知道这几乎可以用了,但是效果不佳.它会显示一张图片,然后显示所有图片的网址文本,而不是相应的文本.

I've got this which NEARLY Works but not quite. It displays an image, then ALL the image urls text, instead of the corresponding one.

{% for image in images %}

        <div class="card" style="width: 18rem;">
          <img src="{{image}}" class="card-img-top" alt="...">
          <div class="card-body">
            {% for title in titles %}
            <h5 class="card-title">{{title}}</h5>
            {% endfor %}
            <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>


          </div>
        </div>
{% endfor %}

我认为只需要进行很小的更改即可工作,但我不知道是什么.

I think only a small change is needed for it to work but I don't know what.

推荐答案

将图像和标题的两个列表一一合并.
对于迭代,解压缩各自元组的两个变量.

Combine the two lists of images and titles one by one.
For the iteration, unpack the two variables of the respective tuple.

import re                          # regular expressions used to match strings
from bs4 import BeautifulSoup      # web scraping library
from urllib.request import urlopen # open a url connection
from urllib.parse import unquote   # decode special url characters

@app.route('/')
@app.route('/home')
def home():
    images=imagescrape()
    # Iterate over all sources and extract the title from the URL
    titles=(titleextract(src) for src in images)

    # zip combines two lists into one.
    # It goes through all elements and takes one element from the first
    # and one element from the second list, combines them into a tuple
    # and adds them to a sequence / generator.
    images_titles = zip(images, titles)
    return render_template('home.html', image_titles=images_titles)

def imagescrape():
    result_images=[]
    #html = urlopen('https://en.wikipedia.org/wiki/Prince_Harry,_Duke_of_Sussex')
    html = urlopen('https://en.wikipedia.org/wiki/Rembrandt')
    bs = BeautifulSoup(html, 'html.parser')
    images = bs.find_all('img', {'src':re.compile('.jpg')})
    for image in images:
        result_images.append("https:"+image['src']+'\n') #concatenation!
    return result_images

def titleextract(url):
    # Extract the part of the string between the last two "/" characters
    # Decode special URL characters and cut off the suffix
    # Replace all "_" with spaces
    return unquote(url[58:url.rindex("/", 58)-4]).replace('_', ' ')
{% for image, title in images_titles %}
    <div class="card" style="width: 18rem;">
      <img src="{{image}}" class="card-img-top" alt="...">
      <div class="card-body">
        <h5 class="card-title">{{title}}</h5>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
{% endfor %}

这篇关于jinja2嵌套for循环两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:11