用 Twig 输出旧形式的数据数组
outputting old form data array with Twig
我正在编写表格。我使用 Select2 允许用户在 select 标签中选择多个选项。如果出现另一个错误,我会将用户重定向回表单并保留用户已经输入或选择的值,这样他就不必再次填写整个表单。
其余字段一切正常,因为我只需使用 request.post('input_name')
函数即可检索发布的信息。
当涉及到这些选择select时,我知道我得到了一个数组。
如果我只进行以下测试,我就知道数组中确实有值:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% endif %}
但是,如果我尝试像这样显示(输出)数据:
{{request.post('select2inputMultiple')}}
它抛出以下错误:
An exception has been thrown during the rendering of a template ("Array to string conversion")
我如何访问该数组的项目?
嗯,看起来它正在工作,我正在尝试使用这样的 foreach 函数:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% for single in request.post('select2inputMultiple') %}
value: {{single}}
{% endfor %}
{% endif %}
并且正在按要求输出数据!
假设您的输入名为 select2inputMultiple[]
,request.post('select2inputMultiple')
是一个数组(如错误所示)。如果没有中介将数组转换为字符串,则无法在页面上显示数组。从 Twig 查看值的最简单方法是使用映射到 var_dump
的 dump
方法。所以你会做
{{ dump(request.post('select2inputMultiple')) }}
假设您有这样的 select 结构:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}">{{ option.name }}</option>
{% endfor %}
</select>
从该数组中 select 这些选项的最简单方法如下:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}"
{% if option.id in request.post('select2inputMultiple') %}
selected
{% endif %}
>{{ option.name }}</option>
{% endfor %}
</select>
我正在编写表格。我使用 Select2 允许用户在 select 标签中选择多个选项。如果出现另一个错误,我会将用户重定向回表单并保留用户已经输入或选择的值,这样他就不必再次填写整个表单。
其余字段一切正常,因为我只需使用 request.post('input_name')
函数即可检索发布的信息。
当涉及到这些选择select时,我知道我得到了一个数组。 如果我只进行以下测试,我就知道数组中确实有值:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% endif %}
但是,如果我尝试像这样显示(输出)数据:
{{request.post('select2inputMultiple')}}
它抛出以下错误:
An exception has been thrown during the rendering of a template ("Array to string conversion")
我如何访问该数组的项目?
嗯,看起来它正在工作,我正在尝试使用这样的 foreach 函数:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% for single in request.post('select2inputMultiple') %}
value: {{single}}
{% endfor %}
{% endif %}
并且正在按要求输出数据!
假设您的输入名为 select2inputMultiple[]
,request.post('select2inputMultiple')
是一个数组(如错误所示)。如果没有中介将数组转换为字符串,则无法在页面上显示数组。从 Twig 查看值的最简单方法是使用映射到 var_dump
的 dump
方法。所以你会做
{{ dump(request.post('select2inputMultiple')) }}
假设您有这样的 select 结构:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}">{{ option.name }}</option>
{% endfor %}
</select>
从该数组中 select 这些选项的最简单方法如下:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}"
{% if option.id in request.post('select2inputMultiple') %}
selected
{% endif %}
>{{ option.name }}</option>
{% endfor %}
</select>