There are ways to neatly isolate preloaded serialized data from the rest of your code.
Example 1—assigning preloaded data to a global variable on window
, and later using it in your table component:
<html>
<meta charset="utf-8">
<body>
<script>
// Loading the data for use in JS components here
(function () {
window.tableData = JSON.parse('{{ table_data }}');
}());
</script>
<script src="table.js"></script>
<!-- table.js uses window.tableData when building the table -->
</body>
Example 2—encapsulate table component as a module, initialize it from the main template and pass the preloaded data.
<html>
<meta charset="utf-8">
<body>
<table id="theTable"></table>
<script src="table.js"></script>
<!-- table.js exports itself globally as window.table -->
<script>
// Loading the data and initializing table component
(function () {
var tableEl = $('#theTable');
var tableData = JSON.parse('{{ table_data }}');
window.table.init(tableData, tableEl);
}());
</script>
</body>
And so on!
Want to completely avoid intermixing Django template language and JavaScript?
- Pass all of your data over XHR—make AJAX requests to the server after your page loads; write a Django view that returns your needed data as JSON which is easy to parse in JavaScript.
Want everything—keep Django template language out and avoid extra XHRs to fetch the data?
- Look into building your app on a framework such as React.js or AngularJS and utilizing server-side rendering of components.