0

I have a real strange problem with twig, I iterate over an array and when I try to 'print' value with {{value}} I get the exception "Array to string conversion" and when I try with {{value.first()}} I get the error "Impossible to invoke a method ("first") on a string variable ("false")" Can someone help me out ?

<select name="select">
 {% for key,value in array %}
   {% if (key !=  'id') and (key != 'type') %}
     <option value={{key}}>{{ key }}: {{ value }}</option>
   {% endif %}
 {% endfor %}
</select>
2
  • What are the values of your array? Could it be that one of your values within the main array is yet another array? Commented Mar 10, 2016 at 11:26
  • You're right I just checked and I have an array in value.. I have no idea how to manage that I mean when it's array make another loop and when it's a string just print the value Commented Mar 10, 2016 at 11:31

1 Answer 1

1

I think the best way to handle this would be to pass the data already flatten to Twig, so it would only need to loop through the data always in the same way.

If that's not possible and you need to use Twig to handle this, you can make use of iterable. This is not pretty, but here we go:

<select name="select">
 {% for key,value in array %}
   {% if (key !=  'id') and (key != 'type') %}
     {% if value is iterable %}
         {% for item in value %}
           <option value={{item}}>{{ key }}: {{ item }}</option>
         {% endfor %}
     {% else %} 
         <option value={{key}}>{{ key }}: {{ value }}</option>
     {% endif %}
   {% endif %}
 {% endfor %}
</select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.