Darc Nawg
Darc Nawg

Reputation: 1655

How to embed python code in Jinja2 template for an image?

I have the following code in which I'm trying to load an jpg image on a page. The image has the primary key id of a database record 1.jpg in this case. I would like to use something like {{ film.id }}.jpg. How to do that? The code below doesn't render the image.

film.id is just the primary key from the record. I want to use it as an reference index number to a corresponding image to its film. Within the tag film.id should expand to an integer. As I have only two films in the database, these should be 1 and 2.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MovieDB</title>
</head>
<body>
{% for film in films %}
    <p>{{ film.title }}</p>
    <img src="{{ url_for('static', filename='img/{{ film.id }}.jpg') }}">
{% endfor %}        
</body>
</html>

I have tried adding the example given by Alex to my views.py:

from flask import render_template, url_for
from app import app
from jinja2 import filters, environment
from app.models import *


@app.route('/')
@app.route('/index')
def index():
    films = session.query(Film).all()

    return render_template('index.html', films=films)

def ufs(film_id):
    return url_for('static', filename='img/{}.jpg'.format(film_id))

app.filters['ufs'] = ufs

It gives the following stack trace:

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from app import app
  File "/Users/jwebster/Code/Python/filmdb/app/__init__.py", line 7, in <module>
    from app import views
  File "/Users/jwebster/Code/Python/filmdb/app/views.py", line 17, in <module>
    app.filters['ufs'] = ufs
AttributeError: 'Flask' object has no attribute 'filters'

Upvotes: 3

Views: 7615

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881705

You need to define a custom filter (and register it with Jinja2) to allow arbitrary Python code to be accessed from within Jinjia2 templates. See http://jinja.pocoo.org/docs/dev/api/#custom-filters for all details.

For example, in your Python server code, at startup:

def ufs(film_id):
    return url_for('static', filename='img/{}.jpg'.format(film_id))

environment.filters['ufs'] = ufs

where environment is your Jinja2 environment, and you have the import to make url_for visible as an unqualified name.

Then, in your Jinja2 template rendered from this environment,

{{ film.id | ufs }}

will expand as you require (if film.id is correct -- it likely would be inside the for, but you've placed it outside, at least in current versions of your Q, which would likely break things for other reasons).

Upvotes: 7

Related Questions