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

asked Jul 30, 2020 at 14:14
1

4 Answers 4

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);
answered Jul 30, 2020 at 14:29
Sign up to request clarification or add additional context in comments.

Comments

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>
answered Jul 30, 2020 at 14:20

2 Comments

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 '<'
@ShinChan When reading the answer, it says: "at the top of your template html file"
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.

answered Jul 30, 2020 at 14:21

Comments

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>

answered Jul 30, 2020 at 14:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.