设置Jinja模板中选择html元素的默认值? [英] Set default value for select html element in Jinja template?

查看:147
本文介绍了设置Jinja模板中选择html元素的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flask/jinja来制作一个简单的Web应用程序.我有一个记录表,该表是从db表中获取的,并由加载记录列表的网页调用.在每一行的一列上都有一个下拉列表(使用select HTML标签完成).

I'm using flask/jinja in order to make a simple web application. I have a table of records which is taken from a db table, and is called by a webpage which loads the list of records. On each row there is a dropdown list (done using the select HTML tag) on a column.

我意识到下面的代码没有实现预期的功能,由于选择了标签,当前自动选择了最后一个选项(第四个).我将其留给尝试展示我要实现的内容.

I realize the below code doesn't do what its supposed to, currently the last option (fourth) is automatically selected because of the selected tag. I've left it in to try show what I'm trying to implement.

理想情况下,我希望它检查当前记录的状态(下面的代码中为rec.status),并根据该状态在下拉列表中选择适当的项.

Ideally I'd want it to check the current record's status (rec.status in the code below) and depending on that, select the appropriate item in the dropdown.

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.您可以尝试执行以下操作,仅打印在正确选项上选择的内容:

You're on the right track - but currently, you're printing selected in all the options in your select box. You can try something like this to only print selected on the correct option:

    <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>

这篇关于设置Jinja模板中选择html元素的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆