I derive an array:

$data= array('text' => 'first', 'text2' => 'second'); return $this->render('SomeBundle:Default:index.html.twig', array('data' => $data)); 

Template:

 {% for qdata in data %} {{ qdata.text }} {% endfor %} 

Mistake:

Impossible to access an attribute ("text") on a string variable ("first") in SomeBundle: Default: index.html.twig at line 2

While the following pattern

 {% for qdata in data %} {{ data.text }} {% endfor %} 

Displays

second

What is the problem?

  • In the array of identical keys. :) It is also impossible. - Bastiane

2 answers 2

Yes, the usual foreach, which is there:

 {% for value in data %} {# 'first' #} {# 'data' #} // {% for key, value in data %} {# 'text', 'first' #} {# 'text2', 'second' #} 

Update

@sargss , well, logic (logic) is no different:

 {{ data['text'] }} {# выведет `first` #} {% for key, value in data %} {% if key == 'text' or key == 'supertext' %} {# выводим только два конкретных элемента, и то, если они существуют #} {{ value }} {% endif %} {% endfor %} 
  • But what if I situationally need to output not all values ​​of the array, but only some? - sargss
 {% for qdata in data %} {{ data.text }} {% endfor %} 

This means: display the value {{data.text}} as many times as there are elements in the data array

BUT there is an error

 {% for qdata in data %} {{ qdata.text }} {% endfor %} 

because qdata is not an element of the data array, but the value of each element of the array. Therefore, it would be correct to:

 {% for qdata in data %} -{{ qdata }}- {% endfor %} 

Displays: "-first - second-" (Dash set to separate the value)