Include django static files in javascript dinamically

I have this situation. I have some bookcovers on my static files on Django. The jpg files names are the isbn of each book. static folder structure

I am building img tags on Javascript and would like to incluide these images to change dinamically. I got each book's isbn already in a variable called "isbn". I am assigning it in this way: var src = "{% static 'img/" + isbn + ".jpg' %}";, and then adding it to the img element. However, the src is been taking as follows: <img id="book-card1img" src="/static/img/%22%20%2B%20isbn%20%2B%20%22.jpg" class="card-img-top">.

Is something I am doing wrong?

The {% static tag will get evaluated first by django server-side, before any javascript runs (because js is run in the browser after django has delivered the page). This means you can't construct tag variables via javascript. Also, if your isbn variable is in javascript, it isn't known when the static tag runs, so it would be taken as a literal string.

Instead you can try

var src = "{{static_prefix}}img/" + isbn + ".jpg"

This does basically the same thing, but allows you more control over the end result, letting js do most of the url construction. See the docs for more

Back to Top