我正在使用flask / jinja来制作一个简单的Web应用程序。我有一个记录表,它从db表中获取,并由加载记录列表的网页调用。在每一行上,列上都有一个下拉列表(使用select HTML标记完成)。
我意识到下面的代码没有做到它应该做的事情,目前最后一个选项(第四个)是由于所选标签而自动选择的。我把它留在了试图展示我正在尝试实现的内容。
理想情况下,我希望它检查当前记录的状态(下面代码中的rec.status),并根据该选项,在下拉列表中选择适当的项目。
HTML:
<tbody>
{% for rec in records %}
<tr>
<td>{{ rec.task }}</td>
<td>
<select>
<option value ="zero" selected={{rec.status==0}}>Zero</option>
<option value ="first" selected={{rec.status==1}}>First</option>
<option value ="second" selected={{rec.status==2}}>Second</option>
<option value ="third" selected={{rec.status==3}}>Third</option>
</select>
</td>
<td><a href={{ "/update_status/"~rec.id}}>Update</a></td>
</tr>
{% endfor %}
</tbody>
谢谢!
你走在正确的轨道上 - 但目前,你正在打印 selected
在您选择框中的所有选项中。你可以尝试这样的东西只打印选择正确的选项:
<select>
<option value="zero"{% if rec.status==0 %} selected="selected"{% endif %}>Zero</option>
<option value="first"{% if rec.status==1 %} selected="selected"{% endif %}>First</option>
<option value="second"{% if rec.status==2 %} selected="selected"{% endif %}>Second</option>
<option value="third"{% if rec.status==3 %} selected="selected"{% endif %}>Third</option>
</select>
你走在正确的轨道上 - 但目前,你正在打印 selected
在您选择框中的所有选项中。你可以尝试这样的东西只打印选择正确的选项:
<select>
<option value="zero"{% if rec.status==0 %} selected="selected"{% endif %}>Zero</option>
<option value="first"{% if rec.status==1 %} selected="selected"{% endif %}>First</option>
<option value="second"{% if rec.status==2 %} selected="selected"{% endif %}>Second</option>
<option value="third"{% if rec.status==3 %} selected="selected"{% endif %}>Third</option>
</select>
对于未来的Google员工:
如果你正在使用WTForms并想在Jinja中设置默认选择,你可能会觉得这样的东西可以工作:
{{ form.gender(class='form-control', value='male') }}
但事实并非如此。也没有 default='male'
也不 selected='male'
(至少在Jinja 2.8和WTForms 2.1中不适合我)。
如果你是绝望的并且不想在你的forms.py中设置它并且不介意得到一点hacky,你可以这样做:
{{ form.gender(class='form-control hacky', value=data['gender']) }}
<script>
var els = document.getElementsByClassName("hacky");
for (i = 0; i < els.length; i++) {
els[i].value = els[i].getAttribute('value');
}
</script>
这使用JavaScript在页面加载时设置它,并允许您传递SelectField中的默认选择,而不必弄乱您的forms.py。在金贾可能有更好的方法,但我还没有找到它。