skip to Main Content

I was trying to pass a variable to my html template in my django project and I can’t seem to find a solution to why it doesn’t work.

The input of username_list: [‘name1’, ‘name2’]

back end:

    username_list = [user.username for user in User.objects.all()]

    return render(response, "main/main-page.html", {"list": username_list})

template:

<script>
    let availableKeywords = {{ list }};
    console.log(availableKeywords);
</script>

The javascript won’t run and I don’t understand if there is another correct way of doing it that I am not aware of.
Can’t figure it out.
Thanks for the help!

2

Answers


  1. To make sure your code works as expected, you should use the json_script template tag to serialize your data properly.

    username_list = [user.username for user in User.objects.all()]
    # Serialize the list as a JSON string
    username_list_json = json.dumps(username_list)
    
    return render(request, "main/main-page.html", {"username_list_json": 
    username_list_json})
    

    Template (main-page.html):

     <script>
        var availableKeywords = JSON.parse('{{ username_list_json|escapejs }}');
        console.log(availableKeywords);
    </script>
    
    • use the json.dumps() method to serialize the username_list as a JSON
      string in the backend.
    • use the {{ username_list_json|escapejs }}
      filter to escape and properly format the JSON string for inclusion in
      JavaScript.
    • parse the JSON string in JavaScript using JSON.parse()
      to convert it into a JavaScript array.
    Login or Signup to reply.
  2. The most secure way will be to use the |json_script template filterĀ [Django-doc]:

    {{ list|json_script:'my_list' }}

    and then process this with:

    <script>
        const list = JSON.parse(document.getElementById('my_list').textContent);
        console.log(list);
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search