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
To make sure your code works as expected, you should use the json_script template tag to serialize your data properly.
Template (main-page.html):
string in the backend.
filter to escape and properly format the JSON string for inclusion in
JavaScript.
to convert it into a JavaScript array.
The most secure way will be to use the
|json_script
template filterĀ [Django-doc]:and then process this with: