2

I'm currently using some Jinja2 templating on my flask app to pull up images on an html page using image paths from a simple sqlite request. I.e. the process is as follows:

1. Retrieve image path from SQLite In SQLite its simply a text field, i.e.:

imagePath text

For example, this would be something like "post1.png"

2. Format a render template for the html page Using url_for, create an image element with the given image path, i.e.:

<img src="{{ url_for('static', filename='assets/images/blog/{{ imagePath }}') }}" alt="" class="img-fluid">

So, I would expect to see something like:

<img src="assets/images/blog/post1.png" alt="" class="img-fluid">

But, instead I'm getting some weird url encoding when the page gets rendered, i.e.:

<img src="/static/assets/images/blog/%7B%7B%20post%5B7%5D%20%7D%7D" alt="" class="img-fluid">

Am I doing something wrong in the templating process? Or is there something I can do to remove all of those hex characters that are generated? I tried passing in a string filter but that didn't seem to work either.

3
  • try printing what imagePath really is Commented Jul 23, 2019 at 17:49
  • Your url encoding translates to {{ post[7] }}. That's not a great choice for a image filename. Commented Jul 23, 2019 at 17:53
  • You cannot nest the curly braces {{ }} so Jinja is escaping them as part of the URL. stackoverflow.com/a/20845452/3357118 discusses an almost identical use case with url_for() Commented Jul 23, 2019 at 18:40

1 Answer 1

5

Jinja2 documentation says:

When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe. Variables and expressions can be marked as safe either in: - the context dictionary by the application with MarkupSafe.Markup, or - the template, with the |safe filter

So, you can try to use safe filter ( http://jinja.pocoo.org/docs/2.10/templates/#safe ):

<img src="{{ url_for('static', filename='assets/images/blog/' ~ imagePath ) | safe }}" alt="" class="img-fluid">

or follow other suggestions from Jinja2 template docs.

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

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.