[Answered ]-Django passing variable to javascript in html template

1👍

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>

0👍

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.

Leave a comment