How to pass python list to JavaScript in Flask app

How to pass a python list to JavaScript with ninja template in Flask web app


You can’t use Python list directly into JavaScript, JavaScript lislt/array is not compatible with Python or wise versa. So what to do.

Solution

I have a list of names, which I want pass to a JavaScript in a Flask ninja template. Ninja template allow use to safely convert the python list to Json string then we can pass it to the JavaScript function / just JavaScript

<script type="text/javascript">

        dn = {{ distabr|tojson }}
</script>

You can’t use same route variable in multiple places in same template, it may not serve the purpose

In JavaScript Functions

Suppose you have separate JavaScript function files for some functionality like drawing analytic plots and pie diagram, or some donut chart. So how do we pass value to those functions ?

You can create a JavaScript as above, in your current template, then in function create a script variable to use it as follows.

function init_echarts() {
    var distNames=dn;
}

That’s all you need to know to embed some morris diagram to your flask app.

You should look at Morris JS , it is free and easy to use JavaScript charts library.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.