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!

4
  • This answer might help. Commented Mar 15, 2017 at 22:48
  • 1
    yeah what they said, you need to put it in the template with the {{data | safe}} filter Commented Mar 15, 2017 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? Commented Mar 23, 2017 at 22:45
  • I added one more stuff that solved the problem: {{data | tojson |safe}} Commented Mar 23, 2017 at 23:11

1 Answer 1

0

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

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.