Reputation: 79
I'm building a webapp using flask
, and am trying to populate a Selectize.js single item select box with a list of countries defined as a Python variable in the flask
app.
Based on this thread, I managed to load a Python list to JavaScript in <script>
tags by using the following code in flask
:
def select():
countries = ["UK", "US", "GER"]
return render_template("select_menu.html", countries = json.dumps(countries))
I am then able to load countries
to be displayed in select_menu.html
using following the JavaScript statement:
var countries = {{countries | safe}}
However, when I try to use this method in combination with Selectize.js, like so:
<script>
$(document).ready(function()
{
var countries = {{countries | safe}};
$("#search").selectize({
valueField: 'val',
labelField: 'val',
searchField: ['val'],
options: countries,
});
});
</script>
No options are loaded. The html part looks like this:
<div class='exampleSearch'>
<select id="search">
<option value="">select</option>
</select>
Additionally, the above Selectize.js codesnippet works just fine when I define countries
in the JS as:
var countries = [{val:"UK"},
{val:"US"},
{val:"GER"}]
Note: defining the Python list in flask
this way did not help.
Can anyone tell me how I should define my Python countries
variable so I could load it into the JS and use it to populate the Selectize dropdown.
Many thanks.
Upvotes: 1
Views: 445
Reputation: 21717
Your Python code is equivalent to the following:
json.dumps(["UK", "US", "GER"])
which will render in JS as a list of strings:
["UK", "US", "GER"]
But the library you are using expects a list of objects:
[{val:"AppleScript"},
{val:"Asp"},
{val:"BASIC"}]
Try replacing your Python select
function with:
def select():
countries = [
{"val": "UK"},
{"val": "US"},
{"val": "GER"}
]
return render_template("select_menu.html", countries = json.dumps(countries))
Upvotes: 2