Import and Use JavaScript in our Django Template

  • To load a JavaScript file in a Django template, you can make use of the `static` template tag provided by Django. Here's how you can do it:
  • In your Django project, make sure you have set up your static files correctly. This typically involves creating a directory named `static` in your project's root directory and adding the `STATIC_URL` settings in your project's settings.py file.
  • Place your JavaScript file in a directory within the `static` directory. For example, if you have a file named `script.js`, you could place it in `static/js/script.js`.
  • In your Django template, load the static template tag library at the top of your template file:


    {% load static %}

  • Use the `static` template tag to reference the JavaScript file in your template. For example, if you want to include `script.js`, you can use the following code:


    <script src="{% static 'js/script.js' %}"></script>

  • The `static` template tag will generate the correct URL for the static file based on the `STATIC_URL` setting in your project's settings.py file. When the template is rendered, the browser will request the JavaScript file from the correct location.
  • Make sure to restart your Django development server after adding or modifying static files for the changes to take effect.
Here is the real complete example:
  • Folder Structure:
  • template/base.html

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>{% block title %}{% endblock %}</title>
    </head>

    <body>
        <header>
            <h1>My Website</h1>
        </header>

        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/app">App</a></li>
            </ul>
        </nav>

        <div id="content">
            {% block content %}
            {% endblock %}
        </div>

        <footer>
            &copy; 2023 My Website
        </footer>
        {% block loadJs %}

        {% endblock %}
    </body>

    </html>

  • template/app/index.html

    {% extends "base.html" %}

    {% load static %}

    {% block title %}App - My Website{% endblock %}

    {% block content %}
    <button onclick="handleFunction(`hello world`)">Click</button>

    <p>This is the content of the Django App page.</p>
    {% endblock %}

    {% block loadJs %}
    <script src="{% static 'js/app/script.js' %}"></script>

    {% endblock %}

  • static/js/app/script.js

    const handleFunction = (param) => {
        console.log("param", param)
    }

  • After clicking button click, print message with param in browser's console screen.

No comments:

Post a Comment