Outputs a Python object as JSON inside of a script
element.
This is the safest way to include data to be used by JavaScript.
Variable
classes = {
'Python': [
'Intro Python', 'Advanced Python', 'Data Science', 'Django'
],
'Databases': [
'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle'
],
'Web': [
'HTML', 'CSS', 'JavaScript'
],
'XML': [
'Intro XML'
]
}
Template
{{ classes|json_script:'classdata' }}
Result
<script id="classdata" type="application/json">{"Python": ["Intro Python", "Advanced Python", "Data Science", "Django"], "Databases": ["Intro PostgreSQL", "Intro MySQL", "Intro SQL Server", "Intro Oracle"], "Web": ["HTML", "CSS", "JavaScript"], "XML": ["Intro XML"]}</script>
You can then use another script
element to consume this content:
<ol>
<script>
const classes = JSON.parse(document.getElementById('classdata').textContent);
pythonClasses = classes['Python'];
for (pythonClass of pythonClasses) {
document.write(`<li>${pythonClass}</li>`);
}
</script>
</ol>
You could (and probably should) point to an external JavaScript file rather than using embedded JavaScript.
Commentary
See Adam Johnson’s Safely Including Data for JavaScript in a Django Template for a detailed explanation of how to safely include dynamic data for JavaScript processing.