0

Hi is there a way to dynamically load different images whenever I get into my flask app? I've got 10 images each is named 'accueil_X' with X is 0,1,2,...

app.py

@app.route('/', methods=("POST", "GET"))
def home():
    random = randrange(10)
    random_pix = 'accueil_'+str(random)+'.png' 

HTML

<img src="{{url_for('static', filename='+{{ random_pix }}+')}}" width=100%, alt="">

Jinja seems to load an image named +{{ random_pix }}+: How can I fix this ? thank you

2 Answers 2

1

so you want to load a random image with each refresh of the home page:

@app.route('/', methods=("POST", "GET"))
def home():
    random = randrange(10)
    random_pix = 'accueil_'+str(random)+'.png'

    [..]
    # i added this missing line to get code more clear
    return render_template('home.html', random_pix=random_pix)

Jinja seems to load an image named +{{ random_pix }}+: How can I fix this ?

it's simple, just remove the {{ }} surrounding the variable random_pix

<img src="{{ url_for('static', filename='\'' + random_pix + '\'') }}" width=100%, alt="">

jinja2 uses {{ .. }} to evaluate any valid expression

refer to this doc

Sign up to request clarification or add additional context in comments.

1 Comment

@userHG if you think my answer solved your issue, please consider giving it the green tick, thx
1

You could do this with a context processor which is the equivelant of Django's "template tag".

This can be used to pass a number of variables to all templates, or pass a function which can then be called in all templates.

First import the required modules, and initialise the app:

from flask import Flask, url_for, render_template
from random import randrange

app = Flask(__name__)

Then define a context processor:

@app.context_processor
def utility_processor():
    def random_image():
        number = randrange(10)
        f = 'accueil_' + str(number) + '.png' 
        return url_for('static', filename=f)
    return dict(rand_im=random_image)

Notice you've passed the random_image function which can then be called in the template as rand_im. Instead of putting the call to url_for in the template, you've done this in Python.

So you could render this with the following in any template:

<img src="{{ rand_im() }}" width="100%" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.