Passing Python Values to JS in Wagtail

Kevin howbrook
Jun 25, 2019 · 2 min read

I was trying to figure out a way to call a JavaScript function using values from the request object. It turns out, Django has a built-in template filter for this…

As an example, I’m going to add some data by overriding the get_context() method on a basic HomePage model (line 19, my_info):

In the home_page.html template, we would normally use this like {{ my_info }} or loop over it depending on what we needed. But if we use the json_script filter, we can safely output this value as JSON…

{{ my_info|json_script:"my-info" }}

Our data is now ready for use with JavaScript. Check the DOM:

Image for post
Image for post

Our data has been added as JSON, wrapped in a script tag, and we can see the data. We can now use this value by looking it up in JavaScript like so:

info = JSON.parse(document.getElementById(‘my-info’).textContent); 

As a bonus… here is an image of the Django rugby team, passing some data to the JavaScript rugby team:

Image for post
Image for post

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store