Home > Software design >  How to inject a variable into <img src='VARIABLE'>
How to inject a variable into <img src='VARIABLE'>

Time:09-29

If I place one of the dictionary values(i.e "https://....) directly into <img src, the image will render properly. Using the variable 'musician'(which contains "https://...) will yield an empty properly formatted frame with a broken image logo.

musician_dict = {
    'g': 'https://media.stubhubstatic.com/stubhub-catalog/d_defaultLogo.jpg/t_f-fs-0fv,q_auto:low,f_auto,c_fill,$w_280_mul_3,$h_180_mul_3/performer/404807/gvwionkcazusra2wbkuu',
    'p': 'https://cdn.britannica.com/18/161418-050-811E4CBE/McCoy-Tyner.jpg?w=400&h=300&c=crop'
}

# The website starts with a main page
@app.route("/")
def piano_or_guitar_game():
    musician = random.choice(list(musician_dict.values()))
    return "<h1>pIANO player or gUITAR player(q to quit)</h1>" \
           "<img src=musician width=500>"

CodePudding user response:

You're sending it back as a string literal. With Flask, you'd usually do something like:

return render_template("index.html", picture=musician)

and then in your templates folder, you would have:

<img src={{picture}} width=500>

See Flask's blog tutorial.

  • Related