L Lawliet
L Lawliet

Reputation: 459

Django: How to pass python variable value to javascript file?

I've a function in views.py which returns latitude and longitude:

return render(request, 'map.html', {'lat_lng':lat_lng})

and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.

I tried all below stack answers but none worked for me:

Django Template Variables and Javascript

Passing django variables to javascript

How to use Django variable in JavaScript file?

Passing Python Data to JavaScript via Django

Upvotes: 0

Views: 1270

Answers (4)

adheus
adheus

Reputation: 4045

One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):

<script type="text/javascript">
    const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>

Upvotes: 1

Sadan A.
Sadan A.

Reputation: 1107

You can take advantage of json_script template tag. In your template do this

{{ lat_lng|json_script:"lat_lng" }}

Then in your javascript file you can access this variable like

const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);

Upvotes: 2

Farouk T.
Farouk T.

Reputation: 51

Be sure when that getting the variable in a script tag is before including the separate js file Exmple :

<script type="text/javascript"> 
   var variable = "{{myV}}";
</script>

<script type="text/javascript" src="myJsFile.js"></script>

Upvotes: 0

schillingt
schillingt

Reputation: 13731

when I try to use lat_lng in separate js file then I'm not able to access it.

You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.

Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.

Upvotes: 0

Related Questions