Symfony 细枝-无法访问空变量上的键(“message”)
好的,首先,我知道有人问过类似的问题 例如: 然而,他们并没有完全回答我的问题。 我正在为我正在编写的应用程序设置登录系统,并且在尝试显示登录验证错误消息时出错 我的模板中有以下代码:Symfony 细枝-无法访问空变量上的键(“message”),symfony,twig,Symfony,Twig,好的,首先,我知道有人问过类似的问题 例如: 然而,他们并没有完全回答我的问题。 我正在为我正在编写的应用程序设置登录系统,并且在尝试显示登录验证错误消息时出错 我的模板中有以下代码: {% if error %} {% block message %}{{ error.message }}{% endblock %} {% endif %} public function loginAction() { $request = $this->getRequest();
{% if error %}
{% block message %}{{ error.message }}{% endblock %}
{% endif %}
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)){
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'SaveSecurityBundle:Security:login.html.twig',
array(
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
这是调用模板的控制器中的内容:
{% if error %}
{% block message %}{{ error.message }}{% endblock %}
{% endif %}
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)){
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'SaveSecurityBundle:Security:login.html.twig',
array(
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
这应该相当简单,但是当我尝试加载登录表单时,我一直收到以下消息:
Impossible to access a key ("message") on a NULL variable ("") in SaveSecurityBundle:Security:login.html.twig at line 5
我尝试转储error
变量,得到了以下结果(我只包括我实际需要的代码行,实际转储是几千行):
所以消息就在那里,但由于某种原因,当它应该传递错误对象时,它传递的是一个空引用
我完全不知道如何解决这个问题,到目前为止,我唯一的解决办法就是删除
错误
打印输出,这将取消通知用户为什么未登录的功能。问题在于,您在细枝块中呈现错误消息,并且无法将块放入if
块中-无论条件如何,它都会呈现
解决方案之一是将块包装到if
语句中:
{% block message %}
{% if error %}{{ error.message }}{% endif %}
{% endblock %}
$request->attributes->get(SecurityContext::AUTHENTICATION\u ERROR)返回一个对象?谢谢您的回答,您完全正确。我没有意识到它会渲染块,而不管
if
语句如何。一旦我把它转过来,它的工作原理和它应该的完全一样。