B
B
BogBel2015-10-08 22:53:20
Flask
BogBel, 2015-10-08 22:53:20

How to pass data from Flask view to HTML?

It is necessary to build a chart according to the data that is transmitted from the view.
Here she is:

@app.route('/hello')
def getting():
    lst = []
    for raw in session.query(DataStoring).descending(DataStoring.population).limit(20):
        lst.append(raw)
    return render_template('chart.html', cities=lst)

For more clarity, I will show another model
class DataStoring(Document):
    _id = StringField()
    city = StringField()
    population = IntField()
    state = StringField()

    mongo_id = _id

    def __str__(self):
        return 'Id=%s City=%s  Population=%s State=%s ' % (self._id, self.city, self.population, self.state)

Actually, like this, I pass the data array to the template
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="/static/style.css">
    <title></title>
    <script src="http://d3js.org/d3.v3.js"></script>

</head>
<body>
{% for city in cities %}
<P>{{ city.city }}:{{ city.population }}</P>
{% endfor %}
<div class="chart"></div>
<script>
   
    var data=[];


    {% for city in cities %}
    
        data.push( {city:{{city.city}}, population:{{ city.population }} });
        console.log({{ city.city }});
        console.log({{ city.population }});
    {% endfor %}


   // var data=[10,20,30,40,50,60,70];
    d3.select(".chart")
  .selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return d/110 + "px"; })
    .text(function(d) { return d.population+d.city; });

</script>

</body>
</html>


At the moment, the area where the {{city.city}} is accessed is important.
When inside <script></script>I try to access this data, I get an error in the browser console.
0e4d831d5bb549d6baeb5c72a26d74e1.png
b69532448cd24530bebfd5ea2ad751ed.png
While if I refer to int population, then everything is fine, there are no errors.
And yet, when I publish information immediately <p></p>outside the script, then everything is fine.
It is very likely that the problem is that there is a space in the title.
Although it's stupid.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question