Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID

Question about foreach loops in templates

edited September 2013 in Framework

If the array {{ array_name }} is empty, {% foreach array_name %}{{ loop_value }}{% endforeach %} throws an error.

Would it be possible for it to silently skip to the next section in the template instead?

Comments

  • It should only throw an error if it's not an array value, an empty array should still work fine. You could also wrap it in an if statement like this:

    {% if is_array ($data->array_name) %}
        {% foreach array_name %}
            {{ loop_value }}
        {% end %}
    {% else %}
        {{ array_name }}
    {% end %}
    
  • edited September 2013

    You're right, it's when it's not set for arrays. But this is giving me an error:

    ./elefant crud-app test id name
    

    Navigate to http://site/tests/admin:

    Debugger::handle_error (2, "Invalid argument supplied for foreach()", "/site/cache/tests-admin.php", 9, array(6))
    
    9 /site/cache/tests-admin.php
    
    7.         <th width="16%">&nbsp;</th>
    8.     </tr>
    9. <?php foreach ($data->items as $data->loop_index => $data->loop_value) { ?>
    10.     <tr>
    11.         <td><?php echo Template::sanitize ($data->loop_value->name, 'UTF-8'); ?></td>
    

    Relevant part of the handler (unmodified, generated by crud-app):

    // Fetch the items and total items
    $items = tests\Test::query ()->fetch ($limit, $offset);
    $total = tests\Test::query ()->count ();
    

    Relevant part of the view (unmodified):

    {% foreach items %}
    <tr>
        <td>{{ loop_value->name }}</td>
        <td style="text-align: right">
            <a  href="/tests/edit?id={{ loop_value->id }}">{"Edit"}</a> |
            <a  href="/tests/delete"
                data-id="{{ loop_value->id }}"
                onclick="return $.confirm_and_post (this, '{"Are you sure you want to delete this test?"}')">{"Delete"}</a>
        </td>
    </tr>
    {% end %}
    
  • Ah yes, the database table doesn't exist so fetch() returns false instead of an array. The example CRUD isn't checking for that condition, but it should so I just added a fix for that:

    https://github.com/jbroadway/elefant/commit/c32d78c427ff7ed8d06916b7f140d9bf48542dea

    Btw, you can import an SQL schema via:

    ./elefant import-db apps/tests/conf/install_sqlite.sql
    

    Cheers :)

Sign In or Register to comment.