【问题标题】:Pre selected in HTML based on context in django template基于 Django 模板中的上下文在 HTML 中预选
【发布时间】:2020-11-27 16:39:42
【问题描述】:

我需要显示一个带有固定选项的选择输入字段

<select multiple>
                        <option > area</option>
                        <option > city</option>
                        <option > project</option>
                        <option > address</option>
                        <option > item3</option>
                        <option > item4</option>
                        <option > anotheritem</option>
                        <option > otheritem</option>
                        <option > lastitem</option>
                        <option > itemrandom</option>
</select>

我在上下文中传递了一个列表,其中包含一个或多个(区域、地址、城市)或全部。 如果选项的任何值出现在传递的上下文列表中,我希望该选项被预选

html 页面将从 django 视图中呈现。最好不要使用表单。

【问题讨论】:

  • 您是否也从后端传递选项,或者它们是硬编码的,只有选定的值会在上下文中传递?
  • 它们是硬编码的。

标签: python html django django-templates


【解决方案1】:
<select multiple>
  <option value="area" {% if "area" in selected_values %} selected {% endif %}> area</option>
  <option value="city" {% if "city" in selected_values %} selected {% endif %}> city</option>
  <option value="project" {% if "project" in selected_values %} selected {% endif %}> project</option>
  <option value="address" {% if "address" in selected_values %} selected {% endif %}> address</option>
  <option value="item3" {% if "item3" in selected_values %} selected {% endif %}> item3</option>
  <option value="item4" {% if "item4" in selected_values %} selected {% endif %}> item4</option>
  <option value="anotheritem" {% if "anotheritem" in selected_values %} selected {% endif %}> anotheritem</option>
  <option value="otheritem" {% if "otheritem" in selected_values %} selected {% endif %}> otheritem</option>
  <option value="lastitem" {% if "lastitem" in selected_values %} selected {% endif %}> lastitem</option>
  <option value="itemrandom" {% if "itemrandom" in selected_values %} selected {% endif %}> itemrandom</option>
</select>

上面的 sn-p 必须完成这项工作,如果你也从后端传递所有选项的列表会更好。 在那种情况下,下面的 sn-p 就可以完成这项工作;

<select multiple>
  {% for option in options %}
  <option value="{{option}}" {% if option in selected_values %} selected {% endif %}> {{option}}</option>
  {% endfor %}
</select>

【讨论】:

  • {% if "area" in selected_values %} selected_values 将是一个列表,因此代码不会像在 django 模板中那样工作,我们无法检查列表中的值,如果我错了,请纠正我。跨度>
  • selected_values 将是例如已经选择的值的列表; selected_values = ["area", "itemrandom", "city", "project"]
猜你喜欢
  • 2023-04-03
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多