Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is it possible to access JavaScript variables in Jinja?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading