lnhubbell
lnhubbell

Reputation: 3365

Trouble Using JavaScript to Insert HTML Img Tag

I'm using the following code:

var oDiv = document.createElement ("DIV");
oDiv.innerHTML='<img src="{{ url_for(\'static\', filename=\'images/bubble4.png\') }}">'

to try and insert an image from my javascript file into my html file. As you can see, I'm using flask. The innerHtml seems to be working because the broken image links do appear. I think the problem is coming from all of the different double and single quotes in flask's url_for syntax, but I can't figure out how to properly escape them. If I manually add the img tag to my HTML, the image shows up just fine.

Any thoughts?

Upvotes: 1

Views: 1183

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122122

The {{ ... }} template tag does not have to worry about quoting in JavaScript, as it'll be replaced by the URL before it is ever interpreted as JavaScript.

In other words, there is no need to escape those quotes:

oDiv.innerHTML = '<img src="{{ url_for('static', filename='images/bubble4.png') }}">';

However, if you are placing this in a JavaScript file located in your static/ folder, then it'll never execute the Jinja2 code; that only applies to dynamic templates, not static assets.

Make sure you put this in a template; you can have your main macro add this URL as a data- attribute to your HTML body, for example:

<body data-bubble-img="{{ url_for('static', filename='images/bubble4.png') }}">

then have you javascript load that:

var bubble_img = $('body').data('bubble-img');
oDiv.innerHTML = '<img src="' + bubble_img + '">';

Upvotes: 4

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

The jinja part is executed on the server, the result is sent to the client, which will then execute (or not...) the javascript code. IOW the jinja part doesn't need any escaping (but you need to make sure the resulting code is properly quoted / escaped).

Upvotes: 0

Related Questions