【问题标题】:jinja2 nested for loops two listsjinja2 嵌套 for 循环两个列表
【发布时间】:2020-07-17 21:32:10
【问题描述】:

我的以下代码在 html 前端没有按照我想要的方式呈现。

{% 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 进行渲染时,图像可以正常工作。

但是,当我尝试添加标题时,基本上是将图像 URL 切片以仅给出部分 URL 文本,在上述格式中,它会弄乱格式,只显示一个图像。

我尝试了各种不同的方法,但都不起作用。

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

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

更新:

我有这个几乎可以工作但不完全。它显示一张图片,然后是所有图片的网址文本,而不是相应的。

{% 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 %}

我认为只需要稍作改动即可使其工作,但我不知道是什么。

【问题讨论】:

  • 我认为您应该事先创建一个图像和标题列表。 images_titles = list(zip(images, titles))
  • 你能把这个作为答案发布吗
  • 也 - 请参阅更新。我有一些东西,几乎可以工作,但只是格式。
  • @Detlef 我真的只是想解决上述问题。

标签: for-loop flask routes jinja2


【解决方案1】:

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

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 %}

【讨论】:

  • 53 vs 58:我不知道标题从哪里开始。我按照你的例子。
  • 我可能需要做更多的字符串操作,因为标题是多种多样的。 title=[image[53:69].strip() for image in images]
  • 每次我做字符串操作 - 首先删除前 58 个字符。 Next 删除最后 60 个字符。我每次都使用图像中的图像吗 -
  • 目前是。从 URL 中提取标题有点复杂。
  • 我无法回答您的下一个问题。尽管如此,我还是想向您发送我不太好的但可能的答案。所以我修改了我对这个问题的回答。希望对你有帮助。
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多