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?

1
  • 1
    You can't use jinja2 in javascript. Simply create your js variable in your html in <javascript> tags, then place your script below and you can use that variable Commented Jun 26, 2020 at 11:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Tried document.write(username); and get error: Uncaught ReferenceError: username is not defined
console.log(username) ?
or try this instead: var username = "{{ username|safe }}"
Please add the comment suggestion to answer - it helped a lot
Is 'var' redundant? (i'm a pythonista and as you can see know little about js)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.