Passing Python Values to JS in Wagtail

Kevin howbrook
Jun 25 · 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:

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:

Photo by Quino Al on Unsplash
Kevin howbrook

Written by

Developer, I also make art and listen to techno https://www.kevinhowbrook.com/