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?

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

stackoverflow.com/questions/8683922/… , I would encourage you to check this out as well.
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

Your Answer

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.