简体   繁体   中英

twig undefined php variable

Hi I've just started to study twig and I've got the following error:

PHP Notice: Undefined variable: message

This is the way i render the view from my controller:

echo $twig->render('/km-profile/km-edit-password.twig', array('error' => $message) );

The variable $message comes from the model and it is an array that looks like

$message = array(
            'message' => 'please fill in all fields!',
            'status' => 'error'
        );

In the view I'm using twig in the following way:

{% if error is defined and error.status == 'error' %}
  <div class="alert alert-danger">{{error.message|raw}}</div>
{% endif %}

The $message variable is only set after I submit the form and detect an error. I know i could put an empty $message array before I start validation in the model, then it will solve the php error message, but I don't understand why I still get it even if I put "is defined" into twig logic.

but I don't understand why i still get it even if i put "is defined" into twig logic

Because the error is not generated from twig but here:

echo $twig->render('/km-profile/km-edit-password.twig', array('error' => $message) );

try

$params = [];
if(!empty($message)) { 
    $params['error'] = $message;
}
echo $twig->render('/km-profile/km-edit-password.twig', $params);

If you have PHP > 7 you can make use of the null coalescing operator too:

echo $twig->render('/km-profile/km-edit-password.twig', ['error' => $message ?? false]);

or with PHP < 7 :

echo $twig->render('/km-profile/km-edit-password.twig', ['error' => isset($message) ? $message : false]);

@Xatenev answer is correct, but I prefer not to make mess in controller code, IMHO it's better to check variable existence in template.

Try this:

{% if error is defined and error.status == 'error' and error.message is defined  %}
  <div class="alert alert-danger">{{error.message|raw}}</div>
{% endif %}

or

{% if error is defined and error.status == 'error'  %}
      <div class="alert alert-danger">
          {%if error.message is defined %}
               {{error.message|raw}}
          {% endif %}
      </div>
{% 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