Twig模板-循环输入


Twig template - looping inputs

我是PHP的Twig模板引擎,但在某些表单的呈现方面存在问题,特别是自动显示"选择"输入的当前选定项。

我正在从数据库中提取某些信息集,它们是:宠物、品种、位置,返回各自的值,例如"猫、狗"。

我不知道如何向用户显示这些输入,因为输入选择值与文本不同,我确实想过使用swtich,但不确定这是否是最佳选择。

这是我当前的代码:

$select = SELECT pet, breed, location FROM...;
$pet = array('cat', 'dog');

然后,页面将使用这些变量呈现视图。

<select class="form-control">
{% for p in pet %}
    {% if p == select.pet %}
        <option value="{{ select.pet }}" selected>{{ select.pet|capitalize }}</option>
    {% else %}
        <option value="{{ p }}">{{ p|capitalize }}</option>
    {% endif %}
{% endfor %}

正如你所看到的,我目前需要依靠"pet"变量来循环输入,这就是我试图改变的,也正如你所见,select的文本只是值,但大写意味着它是有限的。

我如何创建一个不需要数组$pet的trick循环,并允许我指定每个值=>文本,如下所示:

<option value="{{ select.pet }}" selected>Foo dog</option>
<option value="{{ select.pet }}">Bar cat</option>

下面的代码只是一个如何实现您想要的东西的示例。我没有测试它

表格

---------------
| animal_type |
---------------
id [PK]
title

---------------
|   animals   |
---------------
id [PK]
name
animal_type_id [FK, animal_type.id]
breed
birthdate
...

php

<?php
    $animal_types = $animals = [];
    $dbh = new PDO('mysql:host=' . $host . ';dbname=' . $db, $user, $pass);
    //Raise exception on errors
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //Target all available types:
    $stmt_types = $dbh->prepare('SELECT id, title FROM animal_type ORDER BY title');
    if ($stmt_types->execute()) {
        $animal_types = $stmt_types->fetchAll();
    }
    if (isset($_POST['cbo_animal_type']) && is_numeric($_POST['cbo_animal_type'])) {
        $stmt_animals = $dbh->prepare('SELECT * FROM animals WHERE animal_type_id = :animal_type_id ORDER BY name');
        if ($stmt_animals->execute()) {
            $animal_types = $stmt_animals->fetchAll([ 'animal_type_id' => $_POST['cbo_animal_type']);
        }       
    }
    echo $twig->render('path/to/view.html', [
        'animal_types'          => $animal_types,
        'animals'               => $animals,
        'selected_animal_type'  => isset($_POST['cbo_animal_type']) && is_numeric($_POST['cbo_animal_type']) ? $_POST['cbo_animal_type'] : -1,
    ]);

树枝

<form method="POST">
    <select name="cbo_animal_type">
    {% for animal_type in animal_types %}
        <option value="{{ animal_type.id }}"{% if selected_animal_type is defined and selected_animal_type = animal_type.id %} selected{% endif %}>{{ animal_type.title }}</option>
    {% endfor %}    
    </select>
</form>
{% if animals is defined and not animals is empty %}
<ul>
    <li>
        <div>
            <h1>{{ animal.name }}</h1>
            <h2>{{ animal.breed }}</h2>
            <p>
                {{ animal.birthdate }}<br />
            </p>
        </div>
    </li>
</ul>
{% endif %}