为什么出现此错误:未定义的属性:PHP中的Twig_Environment


Why this error: Undefined property: Twig_Environment in PHP?

我在错误登录时尝试将消息从PHP-文件发送到twig-文件时收到此错误:Notice: Undefined property: Twig_Environment::$render in。我想显示来自mu PHP的消息的同一页面-文件如下:

$twig = new Twig_Environment($loader);
echo $twig->render('register.twig');
if (isset($_POST['reg'])) {
    if ($_POST['pwd1'] === $_POST['pwd2']) {
    } else {
        echo ("<script>location.href = $twig->render('register.twig', array('theMessage' => 'Wrong password!'));</script>");
        exit;
    }
}

并且在twig-文件中:

{% if theMessage %}
  {{ theMessage }}
{% endif %} 

但它不起作用,我得到了上面的错误。我在设法解决它时遇到了很大的麻烦。我愿意接受任何建议或暗示。

问题是PHP正在消息中插入$twig变量。最好更改此代码:

echo ("<script>location.href = $twig->render('register.twig', array('theMessage' => 'Wrong password!'));</script>");

对此:

echo sprintf("<script>location.href = %s;</script>", $twig->render('register.twig', array('theMessage' => 'Wrong password!')));