Search code examples
javascriptdjangodjango-templatesdjango-staticfiles

How to pass static js file in django template script?


I want to load the staticfile json that is present in the code into the js to host the swagger.

My index.html:

<HTML>
<head>
{% load static %}
</head>
<body>
<script src="{% static "js/script1" %}"></script>
<script>
var json_contents = // Use the static json `js/json1.json` in here?
</script>
</body>
</html>

How to do the above?


Solution

  • You have misspelled the static template tag

    {% load static %} <!-- not "staticfiles" -->
    <!DOCTYPE html>
    <HTML>
      <body>
      <script src="{% static "js/script1.js" %}"></script> <!-- missed .js extention -->
      <script>
    
        async function load() {
            let url = '{% static "js/json1.json" %}';
            let json_contents = await (await fetch(url)).json();
            console.log(json_contents);
        }
        load();
    
      </script>
      </body>
    </html>
    

    Documentation: Configuring static files