2

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?

Psionman
  • 3,084
  • 1
  • 32
  • 65
  • 1
    You can't use jinja2 in javascript. Simply create your js variable in your html in tags, then place your script below and you can use that variable – token Jun 26 '20 at 11:39

2 Answers2

1

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.

token
  • 903
  • 1
  • 9
  • 23
0

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

castin
  • 294
  • 4
  • 8