Ruth Young
Ruth Young

Reputation: 888

Unexpected identifier when accessing django variable in jquery

I'm just trying to set a variable in jquery so I can change some html and I'm getting the following error:

(index):208 Uncaught SyntaxError: Unexpected identifier

I have checked everything a lot, I have a feeling it will just be an infuriating typo somewhere but I need help I can't stare at it any longer. Here is my jquery:

<script>
// make this document specific and move to another file...?
$( document ).ready(function() {
    //set some variables e.g.
    var1 = 5;
    for ( var i = 0; i < var1; i++ ) {
        // do things
        var2 = 1;
        var3 = 10;
        for ( var j = var2; j <= var3; j++) {
            //more stuff
        }
        var change_start = $('td').filter(function() { 
            return Number(this.textContent) == var2; 
        });

        ///This line is raising an error!!!
        var the_person = {{ person }};

        var add_name = change_start.prepend('<a href="#"><center>'+the_person+'</center></a>');
    }
});

</script>

I've taken a lot out so it's easy to look at. The script worked just fine until I added the last 3 lines so it must be there. For now this script is in the html document, I plan to move it later. I pass person to the template in the view that renders it as shown below:

def holiday(request):
    user = request.user
    # get persons username
    person_id = Person.objects.get(user_name_check=request.user)

    #....


    context = {
        "person": person_id,
        "start_dates": start_list,
        "end_dates": end_list,
        "people": person_list,
    }
    return render(request, "tande/calendar.html", context)

Thanks!

Upvotes: 0

Views: 635

Answers (1)

maikthomas
maikthomas

Reputation: 436

If the variable isn't a JSON object it should be in quotes. see: https://stackoverflow.com/a/4153424/5433407

i.e. var the_person = "{{ person }}";

For now this script is in the html document, I plan to move it later.

Using django template variables won't work if you take this out of the html, see: https://stackoverflow.com/a/32998283/5433407

Upvotes: 3

Related Questions