Search code examples
htmlpython-3.xflaskjinja2web-deployment

Use external link in img src in flask jinja2


I want to use an external link as an image in img tag in HTML in flask. I know how to do it by keeping the images in static folder but my case is different.

I want to do something like below code in index.html:

<body>
    <h1>external image</h1>
    <img src={{url_for('static',filename='https://unsplash.com/photos/uUVkzxDR1D0')}}
      alt="No image">
</body>

My Flask looks like this:

from flask import Flask,render_template

app=Flask(__name__,static_url_path='',static_folder='static',template_folder='templates')

@app.route("/")
def index():
    return render_template("index.html")

I tried removing the static endpoint from the url_for function as it does not makes sense to search for an external image link into static folder, but then I got the error that url_for requires an endpoint.So, I don't know how to put the image link.

Everything is just working fine. Only the image is not getting rendered and I am getting the alt text, i.e., 'No Image' on screen.

Any help would be greatly appreciated. Thanks in advance for the help.


Solution

  • Why not simply:

    <img src='https://unsplash.com/photos/uUVkzxDR1D0'
      alt="No image">
    

    Of course this hotlinks that image from the remote server within your page, which some hosts may disable for their images.