Wednesday, May 23, 2018

Re: Passing values from Python to Javascript

As you can guess this is general problem for all backend languages for passing data to JS. 

AFAIK the standard practice is attaching the value to a DOM element as "data" property and using fetching the value from that element in your JS. If it is a primitive value it is easy to do so, if it is relatively complex structure, e.g. dictionary of classes etc. you can create a string representation of it (maybe in JSON format) and pass it to the template. Check out this link's method #4, it is on .NET but the idea is the same: https://blog.mariusschulz.com/2014/02/05/passing-net-server-side-data-to-javascript.

Hope it helps!

On Wednesday, May 23, 2018 at 4:52:05 AM UTC-7, steve Valet wrote:
I am trying to pass values from Django/Python to Javascript, and have it working to a degree, but need some assistance (obligatory: I'm new to Django so could be hosing this)

I have three files in play here, views.py, app.js, home.html. I can get the values passed to home.html as part of the render, but I can't get the code to work outside of the home.html file. Below is a very simplified example of what I'm doing. 

VIEWS.PY
return render(request, "home.html", {'data':data'})

HOME.HTML

<html>

     <head>

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

          <script>

               myFunction({{ data | safe }});

          </script>

     </head>

</html>


APP.JS

function myFunction(vars){
    return vars
};



I would like to have the JS in the HTML file in the APP.JS file so I can centralize all Javascript, but cannot get it to work outside the HTML. I also tried sending the "data" to JSON using "json.dumps" but got an error that the data was not serializable, so went with this code posted above.

Can I do what I'm trying to do?

Thanks
Steve

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/baeeb802-af22-4534-93ea-378ecbc39f45%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment