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
-
I answered a similiar question like this before. You might want to check this: stackoverflow.com/a/56844921/9958954LearningNoob– LearningNoob2020年07月30日 14:25:11 +00:00Commented Jul 30, 2020 at 14:25
4 Answers 4
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);
Comments
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>
2 Comments
Unexpected token '<'
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.
Comments
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>