GAV
GAV

Reputation: 1213

How to deal with missing values in the array in twig

Some of the values that I'm requesting may or maynot be returning a value as the api takes someones profile and they have left out fields in registration etc.

If I request something which isn't there in my twig template I get the error

 throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type   "%s"     does not exist', $arrayItem, get_class($object)), -1, $this->getTemplateName());

I could solve this by doing this code on each value but it's messy and not clever is there a way of not getting the error, like in other php frameworks, it will just leave a blank

  {% if profile.aboutMe %}

  {{ profile.aboutMe }} 

controller

     return   $this->render('LoginLogBundle:Default:userprofile.html.twig',array('profile'=>$user))); 

Upvotes: 3

Views: 2550

Answers (1)

A.L
A.L

Reputation: 10493

You can use the default() filter to display some text when a object or a value is not defined:

{{ profile.aboutMe|default('No profile') }}
{# or #}
{{ profile.aboutMe|default('-') }}
{# or #}
{{ profile.aboutMe|default('') }}
{# etc. #}

Upvotes: 4

Related Questions