0

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

L Lawliet
  • 419
  • 1
  • 7
  • 20
  • I answered a similiar question like this before. You might want to check this: https://stackoverflow.com/a/56844921/9958954 – LearningNoob Jul 30 '20 at 14:25

4 Answers4

2

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);
Sadan A.
  • 1,017
  • 1
  • 10
  • 28
1

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>
adheus
  • 3,985
  • 2
  • 20
  • 33
  • Thanks for quick response, I am not expert in JS but I think I dont need to use script tag if I am using separate file but though I tried without script tag and it's printing lat_lng as it is and when I tried with script tag I am getting error as `Unexpected token '<'` – L Lawliet Jul 30 '20 at 14:27
  • @ShinChan When reading the answer, it says: "_at the top of your template __html file___" – Teemu Jul 30 '20 at 14:29
0

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>
Farouk T.
  • 51
  • 5
0

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.

schillingt
  • 13,493
  • 2
  • 32
  • 34