Search code examples
pythonflaskjinja2

Insert variable inside img src link in html


So I'm making simple crypto Flask web. I'm trying to display some crypto prices with their icons in live ticker

I have done almost everything but problem comes when I try to upload icons of crypto

Thats my def where I get data from api

def liveTicker():
    url = f'https://api.coincap.io/v2/assets?limit=15'
    data = requests.get(url).json()
    return data['data']

Later I pass it to my html page with render_template, and in html I make a loop to get symbol and price so I can display.

But I don't know how can I update my img src so I can pass {{ item['symbol'].lower() }} inside it replacing "btc" value with all the symbols I get from that api.

>                 <div class="liveticker">
>                     <ul>
>                         {% for item in result %}
>                             <li><img src ="https://assets.coincap.io/assets/icons/btc@2x.png"></a>{{ item['symbol'] }} {{ item['priceUsd'] | float | round(2) }}</li>
>                         {% endfor %}
>                     </ul>
>                 </div>
> 
> 

Any help would be appreciated


Solution

  • Depending on the contents of data["symbol"] (wether it contains the whole URL or only the symbol name), you can only pass the URL of data["symbol"] or prefix it with the domain and path:

    <div class="liveticker">
        <ul>
            {% for item in result %}
                <li><img src ="{{ item['symbol'] }}"></a> {{ item['priceUsd'] | float | round(2) }}</li>
            {% endfor %}
        </ul>
    </div>
    

    or

    <div class="liveticker">
        <ul>
            {% for item in result %}
                <li><img src ="https://assets.coincap.io/assets/icons/{{ item['symbol'] }}"></a> {{ item['priceUsd'] | float | round(2) }}</li>
            {% endfor %}
        </ul>
    </div>