2

I am trying to assign a context dict to a jQuery variable in my django html template and I am getting the following error message in my browser's console:

Uncaught SyntaxError: Unexpected token &

This is how I've assigned the context value (dict) to the javascript variable:

var foo = {{ bar }};

Where bar is the context variable passed from the view

The context is not taken as a javascript object.

Any help is much appreciated.

1
  • post the view too, and do post the full stacktrace Commented Jul 13, 2017 at 15:46

1 Answer 1

0

You can get variable as a string. like below,

var foo = '{{ bar }}';

then you can cast it to the appropriate type. following code will help you to create a json variable using string.

var foo = (("{{ bar |safe}}").replace(/&(l|g|quo)t;/g, function(a,b){
        return {
            l   : '<',
            g   : '>',
            quo : '"'
        }[b];
    }));

foo = foo.replace(/u'/g, '\'')
foo = foo.replace(/'/g, '\"')

var myData = JSON.parse( foo )

Code taken from : Passing objects from Django to Javascript DOM

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

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.