Problem with double {{ }} syntax (one inside second)


I just try to make dynamic path to a folder with photo depending on an object name which is variable.
How should I do this ?
<img src="{{url_for('/{{}}', filename='photo.jpg')}}"/>

I think that before this variable i have to give a special sign …
Can anybody help me ?

Asked By: Dominik Toma



There are a couple reasons you are getting an error.

First, the url_for function requires an endpoint as its argument. You are passing the url_for function the argument '/{{}}' but this string does not resolve to an endpoint.

(The string ‘static’ does resolve to an endpoint, because it’s the name of a Flask function.)

Second, I don’t think you can nest Jinja tags. You are nesting {{ ... }} inside of {{ ... }}.

The proper syntax for building the URL of a static file is this.

<img src="{{ url_for('static', filename='img/photo.jpg') }}" />

Looking at your code, I see that you have a variable called {{}} which gives you the directory of the image.

We can interpolate that variable inside the Jinja tags. There are two ways of doing this.

The first way is to use the {% set %} directive.

{% set folder = {{ }} %}
<img src="{{ url_for('static', filename=folder+'/photo.jpg') }}" />

The second way is to insert directly into the filename assignment.

<img src="{{ url_for('static','/photo.jpg') }}"

I hope this answers your question. The answer attempts to explain the reasons why you are seeing an error, and provide you with two different solutions that you can use.

You have asked a very good question — how do you interpolate a variable inside of Jinja tags? I formed this answer after doing quite a bit of research.

I tested both of these solutions and they worked for me.

It’s fine to have a folder name that is variable… but I think it would help to put the image in the static directory. This way you can make use of the static endpoint when you call url_for.

Your project structure can look like this:

- static
-- <variable_folder_name>
--- photo.jpg
- templates
-- index.html
Answered By: ktm5124
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.