Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token & while rendering a Django template

I'm trying to draw a line chart using "https://www.google.com/jsapi", and passing data from a Django view;

this is my template

<head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);

      function drawChart() {

        data = {{analytics_data}}
        var data = google.visualization.arrayToDataTable(data);

        var options = {
          title: 'Facebook Analytics'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
       <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

views.py

def show_fb_analytics(request):
     analytics_data = [["Day", "Likes", "Share", "Comments"]]
     data = FbAnalytics.objects.all()
     for item in data:
        date = item.date
            likes = item.likes
            comments = item.comments
            shares = item.shares
            lst = [date, likes, comments, shares]
            analytics_data.append(lst)

     return render(request, 'fbchart.html', {'analytics_data':analytics_data})

The analytics_data should return data in format

[['Day', 'Likes', 'Share', 'Comments'],
 ['31 Aug',  5,      8,    10         ],
 ['01 Sep',  10,      5,    13         ]]

but during render of the html template it gives data it given format

[[&#39;Day&#39;, &#39;Likes&#39;, &#39;Share&#39;, &#39;Comments&#39;], 
  [u&#39;01Sep&#39;, 2, 2, 2]]

means it is adding u'&#39 in every string due to which I'm getting the error "Uncaught Syntax Error: Unexpected token &" and my temlate is not returning the line chart. How I can remove this error?

like image 274
Vishnukant Tripathi Avatar asked Dec 25 '22 05:12

Vishnukant Tripathi


1 Answers

You should convert your list to proper JSON first, like this:

import json

def show_fb_analytics(request):
    ...
    return render(request, 'fbchart.html', {'analytics_data': json.dumps(analytics_data)})

Then output it with "safe" filter, so Django's escaping engine doesn't intervene:

{{analytics_data|safe}}

Converting to JSON will output your list as JavaScript Array literal (instead of Python List literal; although the two are pretty similar, they are in fact different, in your case Python has u prefixes which JS doesn't, etc.), and using safe filter will prevent Django's template engine from converting ' to &#39;

like image 176
Spc_555 Avatar answered Dec 27 '22 18:12

Spc_555