0

I have been poking around the web but have not been able to find an example which works for me. It seems as though it is a simple mistake as I have seen multiple examples that are very similar, but when I try following these I keep getting errors (mainly SyntaxError: invalid property id).

Python code (in Django view):

my_dict = {'mykey' : 'myvar'}
jtest = json.dumps(my_dict)
context = {'form': form, 'test_dict' : jtest}

return render(request, "browsefiles.html", context)

Javascript:

<script type="text/javascript">
  var data = {{ test_dict }};
</script>

Error:

SyntaxError: invalid property id

If someone could help me find what is causing this error that would be greatly appreciated. I would like to access the dictionary in the in the javascript code segment.

2
  • 2
    What do you want to achieve? Commented Dec 15, 2015 at 8:17
  • I'd to access the dictionary in the in the javascript code segment. I plan to use variables in the dictionary to create new labels in the html using document.write(). Commented Dec 15, 2015 at 8:22

1 Answer 1

2

Django will escape special characters in your page and the browser cannot recognize the object. You must mark it as safe for Django to leave it alone:

<script type="text/javascript">
  var data = {{ test_dict|safe }};
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I did try that, however it throws yet another error: SyntaxError: expected expression, got '}'
Can you go to "View Source" in you browser and see what django is putting after var data = ...
Ah, I did not realise the variables updated in the inspector. It is presenting the correct dictionary: var data = {"mykey": "myvar"}; But, it is working now, there was a stray curly bracket a couple of lines down that I did not notice which was causing the second error. However, the answer solved the initial problem, so thank you very much!

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.