Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing python list in javascript as an array

Tags:

I have this in my flask views.py

    def showpage():
      ...
      test = [1,2,3,4,5,6]
      return render_template("sample.html",test=test)

I have this in my sample .html

    <script> var counts = {{test}}; </script>

This gives me a empty counts variable. How can I get the counts same as the test list in python?

like image 349
knk Avatar asked Apr 13 '14 03:04

knk


People also ask

Is Python list same as JavaScript array?

Yes. "Object vs Arrays in Javascript is as Python's Dictionaries vs Lists". Performance pros and cons are also the same. With lists being more efficient if numeric indexes are appropriate to the task and dictionaries being more efficient for long lists that must be accessed by a string.

What is Python list in JavaScript?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Can you use lists in JavaScript?

List does not works on javascript.


2 Answers

  1. When you insert variable to template {{ test }} it take object representation. For list of int [1,2,3,4,5,6] it will be rendered as [1, 2, 3, 4, 5, 6], so it is valid javascript array, but this method not safe complex objects without javascript-like representation, for example, test = [1,2,3,4,5,any] will rendered as [1, 2, 3, 4, 5, &lt;built-in function any&gt;], however this is just example and will never work.

  2. To implicitly cast to javascript object in flask exist tojson filter:

    <script> var counts = {{ test|tojson }}; </script>
    

    So if the object is JSON serializable, then all will be rendered, otherwise the template engine will raise an exception.

  3. You also can send javascript code to your template:

    from flask import json
    return render_template("sample.html",test=json.dumps(test))
    

    but it is not a good approach and it's better use tojson filter that is also HTML markup safe.

  4. I prefer to not mix any javascript code within templates and split templates, javascript and javascript data with ajax. If this approach is hard I would prefer to use tojson filter.

like image 161
tbicr Avatar answered Oct 14 '22 13:10

tbicr


You can also use

{{ test|safe }} 

or

{{ test|tojson|safe }}

The safe filter is to be used within script tags.

like image 40
liminal_ Avatar answered Oct 14 '22 14:10

liminal_