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.

Rahul M S
  • 236
  • 2
  • 9

1 Answers1

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

Community
  • 1
  • 1
Chamath Sandaru
  • 412
  • 2
  • 14