Skip to content
Advertisement

Django and JS for loop: how to change a variable value into {%static ‘path’ %}?

I’m trying to find out how to change a path in a picture having JS logic in the Django template. As an example – according to logic in the JS script – change from:

hangman_game/img/s0.jpg to hangman_game/img/s1.jpg then to hangman_game/img/s2.jpg ect

In the previous framework, it was working. But now, I’m migrating a page to the Django framework. Almost all are ready, but JS for loop syntax mentioned previously isn’t working and I’m looking for a way: how to properly set a for loop that will generate a new path to the picture in the HTML file.

in my html file I have:

<div id="gallows">
    <img src="{% static 'hangman_game/img/s0.jpg' %}" alt="" />
</div>

This part is ok. The problem is, that this div is linked to for loop in js file where I previously had:

var errorCount = 0;

if(matched == true)
    {
        
        // errorCount for changing picture:
        errorCount++;
        var picture = "img/s" + errorCount + ".jpg"
        document.getElementById("gallows").innerHTML = '<img src="'+picture+'"alt="" />';

Outside Django, it was working, but after migrating to Django it stopped (obviously).

Because JS var picture is a string, I’m pretty sure that I can use {% static %}, but I don’t know how.

I tried to update the JS file in several ways (without a success). In other words changing this part: enter image description here to:

var picture = "{% static 'hangman_game/img/s" + errorCount + ".jpg' %}"
var picture = "{% static 'hangman_game/img/s' %}{{errorCount+ .jpg}}"
var picture = "{% static 'hangman_game/img/s' %}{{errorCount+ '.jpg'}}"
var picture = "{% static 'hangman_game/img/s' %}{{+errorCount+ '.jpg'}}"
var picture = "{% static 'hangman_game/img/s' %}+errorCount+{{'.jpg'}}"
var picture = "{% static 'hangman_game/img/s' %}+errorCount+{{.jpg}}"

How to implement a proper {% static %} template tag in this for loop?

Advertisement

Answer

I’m not entirely sure what mechanism is behind the solution of this problem, but, after inspection, I realized that the page was unable to find a path in the JS file verbalized as a typical path. It was expected to have a server address as a root: http://127.0.0.1:8000/

So, having in the HTML file:

<div id="gallows">
    <img src="{% static 'hangman_game/img/s0.jpg' %}" alt="" />
</div>

I should have had modyfied part var picture = "img/s" + errorCount + ".jpg" in the js file to:

        errorCount++;
        // var picture = "{% static 'hangman_game/img/s" + errorCount + ".jpg' %}"
        
        var picture = "http://127.0.0.1:8000/static/hangman_game/img/s" + errorCount + ".jpg"
        document.getElementById("gallows").innerHTML = '<img src="'+picture+'"alt="" />';

With that, it works.

Advertisement