Q:

Iterating through loops in twig

I'm trying to iterate through objects in Twig, but am having no such luck.  Here's what I've tried so far. 
Here's my default controller method:
public function ReturnPhonesAction()
    {
        $phonequery = $this->getDoctrine()
        ->getRepository('TravelTravelBundle:Phone')
        ->findAll();

        if($phonequery ! = NULL) {

            return $this->render('TravelTravelBundle:Default:returnphone.html.twig', 
                array('attributes' => $phonequery)
            );        
        }
    }

My Twig:
    {% extends 'TravelTravelBundle::base.html.twig' %}
{% block title %}Return Phone{% endblock %}
{% block body %}    
    {% for key, attribute in attributes %}
        {% if attribute is not empty %} 
            <div class="{{ key }}">
              {{ key|capitalize }}:&nbsp;{{ attribute }}<br /><br />
            </div>
        {% endif %}
    {% endfor %}
{% endblock %}

here's the $phonequery var_dump:
    array(2) 
{
    [0]=> object(Travel\Bundle\TravelBundle\Entity\Phone)#264 (4) {
        ["id":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> int(4) 
        ["name":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(4) "dave" 
        ["phone":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(13) "(801)850-1531" 
        ["email":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(0) "" } 

        [1]=> object(Travel\Bundle\TravelBundle\Entity\Phone)#265 (4) { 
            ["id":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> int(5) 
            ["name":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(5) "Brian"
            ["phone":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(10) "8018952364" 
            ["email":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(13) "dave@dave.com" 
       }
}

I keep getting this error: Catchable fatal error: Object of class Travel\Bundle\TravelBundle\Entity\Phone could not be converted to string
What am I doing wrong here?  It seems to work fine when querying a single row inside the attribute array's value via doctrine's ->findBy.  When I query all rows from mysql via doctrine's ->findAll(); the objects returned are breaking my twig.  What needs to change? 

A:

You are iterating over an array with objects.  Then you print the key and the object.  That means you try to convert an object to a string.  
{# key is string, attribute is the object #}
{% for key, attribute in attributes %}
    {% if attribute is not empty %} 
        <div class="{{ key }}">
                                     {# attribute is still an object, you cannot print it #}
          {{ key|capitalize }}:&nbsp;{{ attribute }}<br /><br />
        </div>
    {% endif %}
{% endfor %}

