I have an HTML file including an embedded script (Javascript). I need to import some lists from Python as variables and I'm having trouble with one that contains strings. To give an example, I have something like the following:
# In Python
list_of_floatnums = [2.5, 3.5, 4.5]
list_of_strings = ["January", "February", "March"]
Then in the script, I do something like this:
<!-- Embedded JS script -->
<script>
var i = 0;
var js_floatnums = JSON.parse('{{ list_of_floatnums }}');
var js_strings = JSON.parse(['{{ list_of_strings }}']);
for (i = 0; i < '{{ number_of_cycles }}'; i++) {
// Do something
}
</script>
However, I get nothing as output. If I skip the JSON.parse() for the string array:
var js_strings = ['{{ list_of_strings }}'];
Then I get everything else to work, except that array of strings (everything is assigned to the first element). For example:
In ["January", "February", "March"] you got 2.5 points.
In undefined you got 3.5 points.
In undefined you got 4.5 points.
Of course what I would require is:
In January you got 2.5 points.
In February you got 3.5 points.
In March you got 4.5 points.
Any clues on what I don't know and I'm doing wrong? I had always imported single variables with {{ variable }}, and that is straightforward.
EDIT:
- I am using Flask.
- number_of_cycles is an integer variable also imported from Python. number_of_cycles = 3 in this case.
number_of_cyclesand please mention what you have write in // Do somethinglist_of_stringsand you are only iterating it withnumber_of_cyclesvar js_floatnums=JSON.parse("{{ list_of_floatnums }}");orvar js_floatnums= {{ list_of_floatnums |tojson }}