简体   繁体   中英

Symfony2 Array to string conversion, set empty value

I`am rendering a twig template in symfony2 and its possible to get a variable with value of array type but i am trying to preview the variable and this error pops:

Array to string conversion ...

So my qustion is not how to print out the array, but is it possible in twig to disable this error, so when an array comes and it cannot be outputed, to set an empty value.

In config.yml, under twig i have set

strict_variables: false

But this dose not include printing arrays.

EDIT:

In controller I pass this array to twig, for example:

'data' => array(
            'description' => array(
                  'desc1', 
                  'desc2'
            )
         );

In twig I am trying to print {{ data['description'] }} and I got the following error:

Array to string conversion ...

This is the normal error that must pop, but I need if I try to print this a no error to pop but instead I need to print nothing(empty value), same way like trying to print an non existing variable with twig set with

strict_variables: false

ANSWER:

Make a custom function:

public function getFunctions()
{
    return array(
       'to_string' => new \Twig_Function_Method($this, 'toString')
    );
}

public function toString($data) {
    if(is_array($data)) {
        return '';
    }
    return $data;
}

And in twig template:

{{ to_string(data['description']) }}

You have two desc: desc1 and desc2 , what do you want to print? If both you have to use this notation (for instance)

 
 
 
  
  {{ data['description'][desc1] }} - {{ data['description'][desc2] }}
 
  

More in general:

 
 
 
  
  {% for desc in data['description'] %} {{ desc }} {% endfor %}
 
  

EDIT

Ok, now I got it (from your comment):

 {% if data['description'] is iterable %} //echo here an empty string {% else %} {{ data['description'] }} {% endif %} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM