Image url in template

I have a template where I show the title field of the records saved in the mysql database

{% for juego in juegos %}
	<h3>{{juego[1]}}</h3>
	<img src="{{ url_for('static', filename='img/services-1.png') }}" class="img-fluid" alt="">         
{% endfor %}

Within that table, I also have a field where I store the path of an image.
What I want is to substitute

{{ url_for('static', filename='img/services-1.png') }}

for something like that

{{ url_for('static', filename='{{game[2]}}') }}

I know that doesn’t work but do you know if there is a similar way?

If game[2] is the name of the field, try:
{{ url_for('static', filename=game[2]) }}

The field game has to be available in the data passed in from your python code or created in the Jinja2 code, e.g. using {% set var='value' %}.

It has not worked for me, it appears in the console

GET /static/ HTTP/1.1" 404 -

What you say about created in the Jinja2 code, how should it be used?

I previously run a mysql query to fetch the fields.

result = cursor.execute("""SELECT id,name,report,role,descripcion,name_img FROM reports_workspace WHERE id_user = %s""", (id_user,))
juegos = cursor.fetchall()

If I put {{game.5}} I get the route but when I put it in src it already gives me an error

<img src="{{url_for('static', filename={{game.5}}) }}" class="img-fluid" alt="">

Once you are in between {{ and }}, you are writing a python expression, so don’t use {{ or }} there.

To quote myself:

Is the field named game in the data passed in from Python? If not: is it created in the template?

If it is, can it be indexed (usually list or tuple) with at least 3 items available?

The game variable comes from the mysql query in python. By referencing game I can show the different fields.

Easiest might be to put the url_for call in your Python code, and pass it along to Jinja as its own template variable (say, img_path). Then it’d be <img src="{{ img_path }}"> in the template, and render_template(..., img_path=url_for(...), ...) in the Python code.

Sorry I got a bit lost.
The render_template syntax in python as it would be?

I currently have

return render_template('home.html', games=games)

would add

return render_template('home.html', games=games,img_path=url_for(...))

But, inside url_for what should I put?

Yep, pretty much what you described. Inside url_for, you would put the exact parameters that you wanted to have in the template, but written as Python rather than as Jinja. So, probably something like this:

img_path=url_for('static', filename=game[2])

But you may need to adjust based on the rest of your code.

I get a console error:

return self.wsgi_app(environ, start_response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2193, in wsgi_app
    response = self.handle_exception(e)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask_login\utils.py", line 290, in decorated_view
    return current_app.ensure_sync(func)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\src\app.py", line 71, in home
    return render_template('home.html', juegos=juegos,img_path=url_for('static', filename=juegos[5]))

I think you cut off the actual exception there - what precisely went wrong?

It might help to post the entire function that’s doing this. I don’t know how your data is structured. Don’t worry about the variable names not being in English - even if I don’t know what “juegos” means, I can figure out what the variable is doing by context :slight_smile:

the circuit is as follows.
I have the following def that does a query

def obtener_report_por_id_user(db,id_user):
    with db.connection.cursor() as cursor:
        juegos = []
        result = cursor.execute("""SELECT id,name,report,role,descripcion,name_img FROM reports_workspace WHERE id_user = %s""", (id_user,))
        juegos = cursor.fetchall()
return juegos

so from def home is where I want to show the images

def home():
    id_user=current_user.id
    juegos = obtener_report_por_id_user(db,id_user)
    return render_template('home.html', juegos=juegos)

I have modified it to

def home():
    id_user=current_user.id
    juegos = obtener_report_por_id_user(db,id_user)
    return render_template('home.html', juegos=juegos,img_path=url_for('static', filename=game[5]))

Ah, okay. I’m not sure what that’s going to return, so it may be helpful to print(juegos) to see what it should be, but it might be that you want this: img_path=url_for('static', filename=juegos[5])

That is exactly what I put but it gives me the error indicated in the previous comment.
In the part of the template what I put is

<img src="{{ url_for('static', filename=img_path) }}" class="img-fluid" alt="">

If I do a game print it shows the following:

((4, 'Panel Export', 'b0aaf7b4-cf40-4c9c-b70c-6c218e48eee5', 'All', 'Ventas por país y clasificadas por producto. Grafico lineal de ventas anuales sin acumular. También hay opciones de filtrado por fecha, país 
y familia de producto.', 'img/services-2.png'), (35, 'Panel Comercial', '9fb695d7-c02b-4f71-939d-22ee54ce79ac', 'All', 'Ventas por cliente y clasificadas por familias. Grafico lineal de ventas anuales sin acumular por mes y acumulado por mes. También hay opciones de filtrado por fecha, zona y comercial.', "'img/services-1.png'"))

The query does it correctly and takes out all the fields, in theory the column I need would be [5]

Ah right. Once you’ve called url_for in the Python code, you don’t need to call it again in Jinja. So your template can be <img src="{{ img_path }}" class="img-fluid" alt=""> without any function call.

I get the following error in console

Traceback (most recent call last):
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2213, in __call__
    return self.wsgi_app(environ, start_response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2193, in wsgi_app
    response = self.handle_exception(e)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask_login\utils.py", line 290, in decorated_view
    return current_app.ensure_sync(func)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\app.py", line 71, in home
    return render_template('home.html', juegos=juegos,img_path=url_for('static', filename=juegos[5]))

I have the following:

def home():
    id_user=current_user.id
    juegos = obtener_report_por_id_user(db,id_user)
    return render_template('home.html', juegos=juegos,img_path=url_for('static', filename=juegos[5]))
<img src="{{ img_path }}" class="img-fluid" alt="">

Hmm, I think you clipped off the actual exception message there. Can you grab another couple of lines from the console please? It should be underlining part of the function call, and then giving a message like NameError or ValueError or something that says what’s wrong.

(If that happens to be in Spanish, that’s fine, I’ll figure it out :slight_smile: )

the console error is:

Traceback (most recent call last):
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2213, in __call__
    return self.wsgi_app(environ, start_response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2193, in wsgi_app
    response = self.handle_exception(e)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask\app.py", line 1469, in dispatch_request     
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\env\Lib\site-packages\flask_login\utils.py", line 290, in decorated_view
    return current_app.ensure_sync(func)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\APP-POWERBY\app.py", line 71, in home
    return render_template('home.html', juegos=juegos,img_path=url_for('static', filename=juegos[5]))
                                                                                          ^^^^^^^^^^^
IndexError: tuple index out of range                         ^^^^^^^^^^^

and this is what I get on the web

Thank you, that’s the part we needed.

So what this is saying is that there’s no juegos[5] - there are fewer than six elements in that tuple. That seems odd, since the query seems to show six columns, but I have a suspicion. You’re calling cursor.fetchall() which should give you a collection of rows - effectively, it gives you a matrix. Since you’re querying one specific user by ID, it may be more useful to use the cursor.fetchone() method, which should give you just one single row. I think that might be what you’re after here.

Failing that, can you print out juegos and show us what it looks like, please?

I use cursor.fetchall() because I want it to fetch me all the rows that match user x.
In the end, what I do is like a menu with all the rows that the user in question has.
If I do the query with cursor.fetchone() I don’t think the other fields will work for me, in the template I go through the resulting rows with a for.