You can use the variables from views.py
in JavaScript, <script></script>
in Django Templates.
For example, if you pass the dictionary with persons
having a list of dictionaries from views.py
to Django Templates as shown below:
# "views.py"
from django.shortcuts import render
def test(request, id=None, slug=None):
persons = [
{'name':'John', 'age':36},
{'name':'David','age':24}
]
return render(request, 'index.html', {"persons":persons})
Then, you can use the variables in JavaScript, <script></script>
in Django Templates as shown below:
# "index.html"
<script>
{% for person in persons %}
console.log("{{ person.name }} {{ person.age}}");
{% endfor %}
</script>
Then, these results are displayed on console:
John 36
David 24
Be careful, if you use a JavaScript's variable and for
loop, unexpected results are displayed on console:
# "index.html"
<script>
let js_persons = "{{ persons }}"
for (let i = 0; i < js_persons.length; i++) {
console.log(js_persons[i]);
}
</script>
Of course, you can use comment
tag in JavaScript, <script></script>
in Django Templates as shown below:
# "index.html"
<script>
{% for person in persons %}
{% comment %}
console.log("{{ person.name }} {{ person.age}}");
{% endcomment %}
{% endfor %}
</script>
# "index.html"
<script>
{% comment %}
{% for person in persons %}
console.log("{{ person.name }} {{ person.age}}");
{% endfor %}
{% endcomment %}
</script>
# "index.html"
{% comment %}
<script>
{% for person in persons %}
console.log("{{ person.name }} {{ person.age}}");
{% endfor %}
</script>
{% endcomment %}