首页 > 解决方案 > Twig 异常,因为在测试它是否为 null 时为 null

问题描述

在数据库中,我有一个可为空的列。当我渲染我的树枝模型时,空值会引发异常。普通的。

但是,当我测试该值是否为空时,它也会抛出异常……因为该值为空。

我的树枝文件中有问题的部分:

{% if musicien.photo is null %}
    <td><img class="img-vignette" src="data:image/jpeg;base64,{{ musicien.photo }}"/></td>
{% else %}
    <td><img class="img-vignette" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABaAFcDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0CiiigDF12xtpp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KioZLhVtjPGrTLgECIZLD2rI0vV5fsEfmWd9O+WzIqAg/Me+e3T8KG0mBu0VHBL50KyGN4938Egww+tVJdWgWV4oYp7l0OGEEe4KfQnpRdAX6KqWmowXUjRASRzKMmKVdrY9cUU07gUbqK4l8REW1yIGFoCWMYfI3nirMGnSi5S4vLtrmSPPljYEVc98DvXDX0jjULkh2z5jDr7mu80ck6RaEnJ8pf5VlF3YyF1VvE0ZZQStoSMjod4pda+7Zf9fkX8642R2/ttvmP/AB8Ede26r/i5mGrqAxA8tT19zS59GB0N6yRa1Zy3OBDsZUZuiyEj8uK0ZZI44meVlWMDkseMVnaciTeHYVlVXBiyQwzXOaXGkms+U6K0YYYVhkD8Kpyt8wOl0IY0/IBWJpHaIEdEJOKTw8R/ZMa5+ZHcMPQ7zWkOBgVx/iJETWVCKqh8FgBjd9fWhvlswOraVZoplt5VaRQR8rZ2nHFU9CeE6ZFHFhXjG2VehD98/jVqxhihtYxFGkYKgkKoGTXP+LY0jKyoirIRy4GCefWm3ZcwGjqpEt/aRWzA3almyOqptOc+nOKKd4dijTT96oqsx+ZgME/WihK+oj//2Q=="/></td>
{% endif %}

例外:

在渲染模板期间引发了异常(“警告:stream_get_contents() 期望参数 1 为资源,给定 null”)。

我的索引函数:

public function index(): Response
{
    if(isset($_POST['search'])){
        $search = $_POST['search'].'%';
    }else{
        $search = '%';
    }

    $musiciens = $this->getDoctrine()
    ->getRepository(Musicien::class)
    ->createQueryBuilder('m')
    ->where('m.nomMusicien LIKE :search')
    ->setParameter('search', $search)
    ->getQuery()
    ->getResult();

    return $this->render('musicien/index.html.twig', array(
        'musiciens' => $musiciens,
    ));
}

它是{% if musicien.photo is null %}抛出异常的行。如果此值为空,我只想显示一个默认值。

标签: symfonyexceptionnulldoctrinetwig

解决方案


代替:

{% if musicien.photo is null %}
  <td>
    <img class="img-vignette" src="data:image/jpeg;base64,{{ musicien.photo }}"/>
  </td>
{% else %}
...

尝试:

{% if musicien.photo is null %}
  <td>
    <img class="img-vignette" src="some_default_photo_because_musicien_deosnt_have_one"/>
  </td>
{% else %}
...

现在,您基本上是在检查 photo 是否为空,然后尝试打印。


推荐阅读