Assign Django Template Variable to a JavaScript Variable

  • In Django templates, you can assign a Django template variable to a JavaScript variable by using template tags and the JavaScript code block.
Here's an example of how you can do it:
  • views.py


    from django.shortcuts import render

    def handleHome(request):
        return render(request, "app/index.html", {"myvariable": "hello world"})

  • Now use 'myvariable' variable into django template.


    <button onclick="handleFunction(`{{myvariable}}`)">Click</button>

    <h1>{{myvariable}}</h1>

    <script>
        console.log("hii", "{{myvariable}}")
    </script>

  • Make sure to include the `<script>` tag within a Django template file (with a `.html` extension) where you have access to the Django template context and variables.
  • Note that this approach assumes the variable `myvariable` contains a string value. If you need to pass complex data structures such as lists or dictionaries, you can convert them to JSON format using Django's `json_script` template filter and then parse the JSON data in JavaScript.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...