【问题标题】:Impossible to access an attribute ("nom") on a null variable无法访问空变量的属性(“nom”)
【发布时间】:2020-01-05 19:35:49
【问题描述】:

我希望我的每个孩子都显示他们的照片,但我收到了以下错误消息:

无法访问空变量的属性(“nom”)。

在我的树枝上:

{% for eleve in eleves %}
  <div><img src="{{ asset('img/')~eleve.image.nom}}" alt="" width="200" height="200"></div> 
  <div>{{eleve.prenom}}</div>                             
{% endfor %}

在我的控制器中:

/**
 * @Route("/accueilPrincipal", name="accueilPrincipal")
*/
public function eleve(Request $request, EntityManagerInterface $manager)
{
    // On récupere tous les eleves
    $repo = $this->getDoctrine()->getRepository(Image::class);
    $repo2 = $this->getDoctrine()->getRepository(Eleve::class);
    $images = $repo->findAll();
    $test = $repo2->findAll();

    $sexe = $this->getUser()->getSexe();
    $eleves = $this->getUser()->getElevestuteur1();
    $eleves2 = $this->getUser()->getElevestuteur2();

    $user = $this->getUser()->getNom();

    return $this->render('profile/accueilPrincipal.html.twig', [
        'eleves' => $eleves,
        'eleves2' => $eleves2,
        'user' => $user,
        'sexe' => $sexe,
        'images' => $images,
        'test' => $test,
    ]);
}

【问题讨论】:

  • 你能提供 Eleve 类的代码吗?模板很可能应该是 eleve.nom 而不是 eleve.image.nom
  • 嗨,我想要的不是学生的名字,而是他的照片`。
  • 使用 VarDumper 组件查看模板中变量的内容 (symfony.com/doc/current/templating/debug.html)。错误消息表明您的一位学生没有图像。您可以首先确保所有学生都有图像,或者使用 Twig 的默认过滤器 (twig.symfony.com/doc/2.x/filters/default.html)。
  • 旁注:您应该先构建路径,然后将其传递给资产函数(不要在资产调用的结果中附加一些片段)。您现在可能不会使用它的所有魔力(例如symfony.com/doc/current/reference/configuration/…),但它可能会为您省去麻烦。

标签: php symfony variables


【解决方案1】:

检查$eleves 变量,它应该更清晰。 dump($eleves);die; 之前的 return $this-&gt;render(...) 将向您展示实际存在的内容,而不是您认为必须存在但您不太知道的内容。

【讨论】:

  • 只有此答案中的最后一段与实际问题有关。 (不在模板中使用变量不需要打扰控制器;Twig 可以使用相同的语法访问数组和对象,因此在代码显然是面向对象的情况下在这里引用数组是令人困惑的;“tuteur”是导师,那么是什么让你认为结果是一个 URL?)
猜你喜欢
  • 2022-07-07
  • 2017-11-17
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多