is it possible to access JavaScript variables in Jinja?

How can I access javascript variables in the jinja template?


    let data_str = "video1";
    let url = `{% url "renderVideo" args="${data_str}" %}`


path("videoplay/<str:args>", views.videoplay, name="videoplay")


Internal Server Error: /videoplay/${data_str}

I’m expecting /videoplay/video1 but it is not parsing the JavaScript variable.

>Solution :

TL;DR: No, Jinja and JS are separate processes.

Long version:

I think you have a misunderstanding of how templating (Jinja) works.

There are two parts of a Django web application, the backend (Django and Python) and the frontend (HTML/CSS/JS). This extends off of the client-server model. When the browser/client requests a webpage, it sends a request to the backend/server. The backend/server then does some processing (in this case, in Python) and sends back a result to the browser/client in the form of HTML/CSS/JS. The client can show HTML, style it with CSS, and execute some JS. Executions on the backend/server and frontend/client are completely separate.

Jinja is a templating engine. Remember when I said the backend does some processing? Well, this is it. Simply put, Jinja takes a generic HTML/CSS/JS template and fills in the blanks with some Python variables. It then sends the result over to the browser. Once the HTML/CSS/JS reaches the browser, it displays the HTML, styles it with CSS, then executes any JS it gets.

The browser never sees the Jinja template, because it only gets the "filled in" version. And conversely, Jinja cannot access JavaScript variables because the JavaScript hasn’t been executed yet.

Leave a Reply