How can I avoid this Unexpected token error when using django/javascript?

Viewed 156

I am trying to pass some data from my django app into a javascript following the answers this question

views.py

context['username'] = json.dumps(request.user.username)

test_script.js

document.write('Script working')
username = {{ username|safe }};

But in console I get the error

Uncaught SyntaxError: Unexpected token '{'

What am I missing?

2 Answers

Let's say this is your HTML:

<html>
  <body>
    .
    .
    .
  </body>
  <script>
    var username = "{{ username|safe }}"
  </script>
  <script src="path/to/your/script.js"></script>
</html>

Place your username variable in your html, then you can access it in your script file.

Django already has a solution for this. In your template,assuming you are extending the base template

....
{{ username|json_script:'username'}}

Then inside your javascript file

var username = JSON.parse(document.getElementById('username').textContent)

For more information about json script check out https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script

Related