3

I am building a web site using flask. In the app.py file, I calculated out some stats that are passed to the html page.

@app.route('/')
def index():
    values = [10, 11, 7, 15, 19, 5, 7.5, 10.9]
    days= ["12/18/18","12/25/18","1/1/19","1/8/19","1/15/19","1/22/19","1/29/19","2/5/19"]

return render_template('index.html', days = days, values=values)

The javascript in the index.html is as follows

var ctx = document.getElementById("lineChart");
var lineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: {{days}}
    datasets: {
      label: "All users",
      backgroundColor: "rgba(30,144,255, 0.31)",
      borderColor: "rgba(30,144,255, 0.7)",
      pointBorderColor: "rgba(30,144,255, 0.7)",
      pointBackgroundColor: "rgba(30,144,255, 0.7)",
      pointHoverBackgroundColor: "#fff",
      pointHoverBorderColor: "rgba(220,220,220,1)",
      pointBorderWidth: 1,
      data: {{values}}
    }
  },
});

I tested two options in the javascript:

  1. Not working (can't generate the chart plot)

    labels: {{days}}
    data: {{values}}
    
  2. Working if I explicitly give list of strings

    labels: ["12/18/18","12/25/18","1/1/19","1/8/19","1/15/19","1/22/19","1/29/19","2/5/19"]
    data: {{values}}    
    

It seems that passing the numeric arrays (values in this example) is fine but passing the list of strings will cause trouble.

Do you have any suggestions to address the issue?
Much appreciated!

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
Lingbo
  • 31
  • 1
  • 7
  • This [answer](http://stackoverflow.com/a/15322060/2800058) might help. – pjcunningham Mar 15 '17 at 22:48
  • 1
    yeah what they said, you need to put it in the template with the `{{data | safe}}` filter – reptilicus Mar 15 '17 at 22:53
  • Thanks! The 'safe' method solves the problem when I am hosting the app in my local windows pc! But it fails if I deploy it in the Ubuntu machine using Apache2.. Do you know what might be cause? – Lingbo Mar 23 '17 at 22:45
  • I added one more stuff that solved the problem: {{data | tojson |safe}} – Lingbo Mar 23 '17 at 23:11

1 Answers1

0

Put the jinja values in double quotes. That works. Write "{{values}}" instead of {{values}}.

Adrian W
  • 4,563
  • 11
  • 38
  • 52