0

I know how to send data from Django to html with the view

def index(request):
    coord = "[[1, 2], [2, 1]"
    return render(request, 'index.html', {'coord': coord})

In the html I able to use it any where like this {{ coord }}, example :

<script type="text/javascript">
     var geojsonObject = {
         "coordinates": {{ coord }}
     };
</script>

But when I try to do this in my 'index.js' I get an error:

Uncaught SyntaxError: Unexpected token '{'

index.html

<script src="{% static 'index.js'%}"></script>

index.js

var geojsonObject = {
         "coordinates": {{ coord }}
};

I could keep everything in index.html, but I find it not practical to debug. How can I pass my coor object to the JavaScript through html?

BeGreen
  • 765
  • 1
  • 13
  • 39

1 Answers1

1

Are you sure you wanna "render" your index.js? I guess a better approach would be to modify your index.js so that if accepts the templated value as a variable. For example:

index.html

<button onclick="doStuff({{ coord }})">Button</button>

index.js

function doStuff(coord) {
    var geojsonObject = {
         "coordinates": coord,
    };
}
  • In this way you don't need to copy all your code to the index.html file either.
  • Otherwise, you could just pass an ID to the element you are templating the value into, and then use document.getElementById("myElement").innerHTML to access it's value.
Rohan Mukherjee
  • 280
  • 2
  • 7
  • https://stackoverflow.com/questions/8683922/how-can-i-pass-my-context-variables-to-a-javascript-file-in-django , I would encourage you to check this out as well. – Rohan Mukherjee May 31 '20 at 23:12
  • I've oversimplified my view and removed everything in it. Thing is I have nothing un my `html`, the only button of my form is generated by python, the view sends the form to the `html`. I'll check if I can use the function in an other way. thx – BeGreen May 31 '20 at 23:19