user1592380
user1592380

Reputation: 36247

Passing data to a view with flask

I'm working with flask and handsontable. I'm interested in dynamically creating data and then passing it to a view for display with handsontable.

So far I have :

@app.route('/mv')
def my_view():

    pq = my_object()
    for p in pq:
        print str(p._data)

    return render_template('my_view.html', page_title = 'nothing yet')

if __name__ == '__main__':
    app.run()

The print statement generates a dictionary of keys values for each object that looks like:

 {u': False, 'delete_at': 1438759341.674, 'id': 43, 'fa': 0, 'created_at': 1438701741.674 }
 {u': False, 'delete_at': 1438759341.675, 'id': 44, 'fa': 0, 'created_at': 1438701741.675 }
 {u': False, 'delete_at': 1438759341.675, 'id': 47, 'fa': 0, 'created_at': 1438701741.675 }

I'd like to pass this data in to the view, preferably as JSON. How can I do this?

Upvotes: 2

Views: 6118

Answers (1)

Brobin
Brobin

Reputation: 3326

You simply add the named parameter to the render_template call.

import json

@app.route('/mv')
def my_view():

    pq = my_object()

    # put all of the data into a list
    data = [p._data for p in pq]

    # render the template with our data
    return render_template('my_view.html', page_title = 'nothing yet', data=data)

if __name__ == '__main__':
    app.run()

Then you can access the value of data in your template (I'm assuming you're passing it into javascript).

<html>
<body>
    <script>
        var data = JSON.parse('{{ data | tojson }}');
        // do stuff with the data
    </script>
</body>
</html>

Upvotes: 6

Related Questions