codingnewbie12345
codingnewbie12345

Reputation: 11

Python Variables in HTML

I recently coded a script that scrapes headlines and images off of https://thestar.com ( The Toronto Star ), It takes the first 10 h3 elements from the site and the corresponding images ( 10 img elements ), and displays them on my news aggregator website.

However , my index.html file is having a problem.

enter image description here

As you can see, instead of displaying the images in order by its corresponding headline, its just displaying ALL of the images in every single headline.

All i need is for each image from the 10 images seen in the screenshot i put up above to show one by one in order next to each headline.

Here's the code for the container element that is displaying the headlines and images in my html file :

<div class="col-6">
        <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
        {% for n in toi_news %}
        <strong><h5>{{n}}</h5></strong>
        {% for i in images %}
        <img src="{{i}}">
        {% endfor %}
        <hr>
        {% endfor %}
        <br>
    </div>

Can anyone help me? Any help would be greatly appreciated.

Upvotes: 0

Views: 63

Answers (1)

Musa
Musa

Reputation: 97672

You need to loop through the images and the headlines concurrently not nesting the image loop in the headline loop.

<div class="col-6">
    <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
    {% for i, n in zip(images, toi_news) %}
    <strong><h5>{{n}}</h5></strong>
    <img src="{{i}}">
    <hr>
    {% endfor %}
    <br>
</div>

If you cant you the above syntax you can loop over an index for both lists

<div class="col-6">
    <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
    {% for x in range(len(toi_news)) %}
    <strong><h5>{{toi_news[x]}}</h5></strong>
    <img src="{{images[x]}}">
    <hr>
    {% endfor %}
    <br>
</div>

Upvotes: 1

Related Questions