Passing Python Values to JS in Wagtail

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:

Developer, I also make art and listen to techno

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