is it possible to access JavaScript variables in Jinja?

Question:

How can I access javascript variables in the jinja template?

Example:

<script>
    let data_str = "video1";
    let url = `{% url "renderVideo" args="${data_str}" %}`
</script

url:

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

Traceback:

Internal Server Error: /videoplay/${data_str}

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

Asked By: Jocefyneroot

||

Answers:

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.

Answered By: Michael M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.