Twig递归菜单

时间:2015-06-06 10:19:53

标签: loops frameworks twig slim

我有这张桌子

id | Type_number | Number
1    fax           01234
2    mobile        789-123
3    phone         000-555
4    fax           022354
5    phone         000-687

我需要按类型分组并按类型列出分组中的数字

示例

FAX
01234
022354

mobile
789-123

phone
000-555
000-687

如果我有这个代码:

<div class="colour_container">
{% for rec in list_number if rec.type == "fax" %}
{{ rec.type_number }}    {{ rec.number }}
{% endfor %}
</div>
    <div class="colour_container">
{% for rec in list_number if rec.type == "phone" %}
{{ rec.type_number }}    {{ rec.number }}
{% endfor %}
</div>

循环&#34; for&#34;仅适用于第一个循环&#34;传真&#34;在第二个没有。 为什么?

1 个答案:

答案 0 :(得分:0)

它对我有用。试试这个例子。

<强>的index.php

<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Twig()
));

$view = $app->view();

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension()
);

$view->parserOptions = array(
    'debug' => true
);

$menu = array(
    array(
        "id" => 1,
        "type" => "fax",
        "number" => "01234"
    ),
    array(
        "id" => 2,
        "type" => "mobile",
        "number" => "789-123"
    ),
    array(
        "id" => 3,
        "type" => "phone",
        "number" => "000-555"
    ),
    array(
        "id" => 4,
        "type" => "fax",
        "number" => "022354"
    ),
    array(
        "id" => 5,
        "type" => "phone",
        "number" => "000-687"
    )
);

$app->get('/', function () use($app, $menu) {
    $app->render('index.twig', array(
        'list_number' => $menu,
        'types' => array("fax", "mobile", "phone")
    ));
});

$app->run();

<强> index.twig

<div class="colour_container">
    {% for type in types %}
        {% set printed = false %}
        {{ type }}
        <br/>
        {% for rec in list_number if rec.type == type %}
            {{ rec.number }}<br/>
        {% endfor %}
        <br/>
    {% endfor %}
</div>