HTML select options from a python list
<p>I'm writing a python cgi script to setup a Hadoop cluster. 
I want to create an HTML select dropdown where the options are taken from a python list. Is this possible?? 
I've looked around a lot. Couldn't find any proper answer to this.</p>

<p>This is what i've found so far on another thread...</p>

<pre><code>def makeSelect(name,values):
    SEL = '&lt;select name="{0}"&gt;\n{1}&lt;/select&gt;\n'
    OPT = '&lt;option value="{0}"&gt;{0}&lt;/option&gt;\n'
    return SEL.format(name, ''.join(OPT.format(v) for v in values))
</code></pre>

<p>I really need some help. Please. Thanks.</p>

<p>You need to generate a list of "option"s and pass them over to your javascript to make the list</p>

<pre><code>values = {"A": "One", "B": "Two", "C": "Three"}
options = []

for value in sorted(values.keys()):
    options.append("&lt;option value='" + value + "'&gt;" + values[value] + "&lt;/option&gt;")
</code></pre>

<p>Then inject "options" into your html. Say, in your "template.html" there is a line:</p>

<pre><code>var options = $python_list;
</code></pre>

<p>Then at the end of your python script:</p>

<pre><code>####open the html template file, read it into 'content'
html_file = "template.html"
f = open(html_file, 'r')
content = f.read()
f.close()

####replace the place holder with your python-generated list
content = content.replace("$python_list", json.dumps(options))

####write content into the final html
output_html_file = "index.html"
f = open(output_html_file, 'w')
f.write(temp_content)
f.close()
</code></pre>

<p>In your "index.html", you should have one line after "var options = ..." that takes the list and generate the dropdown.</p>

<pre><code>$('#my_dropdown').append(options.join("")).selectmenu();
</code></pre>

<p>Alternatively, I suggest that you use your python to generate a json file (with json.dumps()), a file called "config.json" maybe. And your html javascript file should read this json file to render the final page. So in your json file, there should be something like:</p>

<p>{ ... "options": ["One", "Two", "Three"] ...}</p>

<p>And in your html  section, you could read the option values</p>

<pre><code>d3.json("config.json", function(data)) {
 var options = [];
 for (var i= 0; i &lt; data.options.length; i++)
    {
      options.push("&lt;option value='" + data.options[i] + "'&gt;" + data.options[i] + "&lt;/option&gt;");

    }
 $('#my_dropdown').append(options.join("")).selectmenu();
}
</code></pre>

python html cgi