Skip to Content
Mastering Flask Web Development - Second Edition
book

Mastering Flask Web Development - Second Edition

by Daniel Gaspar, Jack Stouffer
October 2018
Intermediate to advanced
332 pages
8h 9m
English
Packt Publishing
Content preview from Mastering Flask Web Development - Second Edition

The tojson filter

We use the tojson filter to pass the variable to the Python json.dumps function, as shown in the following code. Remember that your passed object must be serializable by the json module:

{{ {'key': False, 'key2': None, 'key3': 45} | tojson }} 
{key: false, key2: null, key3: 45} 

This feature is most commonly used to pass SQLAlchemy models to JavaScript MVC frameworks upon the loading of the page load than waiting for an AJAX request. If you use tojson in this way, remember to pass the result to the safe filter as well to make sure that you don't get HTML escape sequences in your JavaScript. Here is an example with a collection of models from Backbone.js, a popular JavaScript MVC framework:

var collection = new PostCollection({{ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Flask Web Development, 2nd Edition

Flask Web Development, 2nd Edition

Miguel Grinberg
Flask Web Development

Flask Web Development

Miguel Grinberg

Publisher Resources

ISBN: 9781788995405Supplemental Content