JJ7907
JJ7907

Reputation: 45

Stop jinja from converting string to url encoding?

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.

Upvotes: 1

Views: 5488

Answers (1)

Sergei Sadovnikov
Sergei Sadovnikov

Reputation: 376

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.

Upvotes: 4

Related Questions