为动态生成的HTML标记分配ID


Assigning IDs to dynamically generated HTML tags

我使用的是Symfony 2 PHP框架和Twig。我的问题是:

我必须生成可变数量的<select>元素。然后,每个选择都显示了一组选项,用户必须从中选择一个。因此,我想以某种方式为这些<select>元素中的每一个分配一个id属性,这样我就可以为每个元素获得所选的选项。

我一直在四处寻找,尝试不同的东西,但到目前为止没有任何效果。

我的代码看起来像这样:

<form action="" method="POST" id="selectForm">
    {% for i in 1..11 %}
        <select class="select" id="select{{ i }}">
            <option disabled selected> --Select a player -- </option>
                {% for item in items %}
                    <option>...</option>
                {% endfor %}
        </select></br>
    {% endfor %}
    <button class="btn btn-primary" id="updateButton">Update</button>
</form>

正如您所看到的,我最近尝试使用Twig变量i,它迭代for循环以设置id,但似乎不起作用。

您应该将变量与字符串连接起来,而不是将其打印为

<form action="" method="POST" id="selectForm">
    {% for i in 1..11 %}
        {% set sid = "select"~i %}
        <select class="select" id=sid>
            <option disabled selected> --Select a player -- </option>
                {% for item in items %}
                    <option>...</option>
                {% endfor %}
        </select></br>
    {% endfor %}
    <button class="btn btn-primary" id="updateButton">Update</button>
</form>