您需要生成一个“选项”列表并将它们传递给您的 javascript 以制作列表
values = {"A": "One", "B": "Two", "C": "Three"}
options = []
for value in sorted(values.keys()):
options.append("<option value='" + value + "'>" + values[value] + "</option>")
然后将“选项”注入到您的 html 中。说,在你的“template.html”中有一行:
var options = $python_list;
然后在你的 python 脚本结束时:
####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()
在您的“index.html”中,您应该在“var options = ...”之后有一行,用于获取列表并生成下拉列表。
$('#my_dropdown').append(options.join("")).selectmenu();
或者,我建议你使用你的 python 生成一个 json 文件(使用 json.dumps()),一个名为“config.json”的文件可能。并且您的 html javascript 文件应读取此 json 文件以呈现最终页面。所以在你的 json 文件中,应该有这样的内容:
{ ...“选项”:[“一”,“二”,“三”] ...}
在您的 html <script> 部分,您可以读取选项值
d3.json("config.json", function(data)) {
var options = [];
for (var i= 0; i < data.options.length; i++)
{
options.push("<option value='" + data.options[i] + "'>" + data.options[i] + "</option>");
}
$('#my_dropdown').append(options.join("")).selectmenu();
}