Lleims
Lleims

Reputation: 1353

Use python variables in a external js file. Django

I'm working in a Django project and I would like to have it tidy. Thus I decided (among other things) don't have de css styles and js scripts inside the html templates. With the css styles I have no problems, I have created a css folder inside the static folder and I save all my css files inside, it works perfectly.

My problem comes when I want to do the same with the js files that works with the python variables that comes from the views.py. Because it don't recognise they. How can I import this variables to the js external files?

Now I have this, but it don't works.

main.html

{% load static %}

<!DOCTYPE html>
<html lang="es">
    <head>
        <title> {% block title%}{% endblock%} </title>

        <meta charset="utf-8">

        <link rel="stylesheet" type="text/css" href="{% static "/css/main.css" %}">
        <link rel="stylesheet" type="text/css" href="{% static "/css/data.css" %}">

    </head>
    <body>
        <h1> WELCOME HOME </h1>
        <p>{{Data}}</p>

        /* This script has to be in a external js file. HERE WORKS
        <script>
            alert('{{Data}}');
        </script>*/

        {% block content %}{% endblock%}

        <script type="text/javascript" src="{% static "/js/data.js" %}"></script>
    </body>
</html>

data.js

alert('{{Data}}')
//alert({{Data}}) ERROR

If the alert has no python variables like alert("Hello world") it works well, but when I pass a Python variable it shows '{{Data}}'.

Thank you!

Upvotes: 2

Views: 1664

Answers (2)

Kabali
Kabali

Reputation: 382

we can do this in two ways..

1.

add the below line in your html file

{{ value|json_script:"mydata" }}

and fetch the above value to data.js file as below

var value = JSON.parse(document.getElementById('mydata').textContent);

2.

add the following tag at the below of this line

   <script type="text/javascript">
       var data= '{{ data }}' 
   </script>
   <script type="text/javascript" src="{% static '/js/token.js' %}"> 
   </script>

and you can fetch it like as usual javascript variable as follows in data.js file

 alert(data);

Upvotes: 6

rahul.m
rahul.m

Reputation: 5854

you can pass it through function

try this

html :

demo({{var}})

js :

demo(var){
    alert(var)
}

hope it helps

Upvotes: 1

Related Questions