Laravel Blade {{ $variable 或 'Default Text' }} 无法使用 URL

Laravel Blade {{ $variable or 'Default Text' }} not working with URLs

我有以下循环遍历用户帐户并显示它们的代码:

@foreach ($accounts as $account)
<tr>
    <td class="user-image hidden-xs hidden-sm">
        <a href="#">
             <img src="{{ $account->profile_pic_url or '/profiles/anonymousUser.jpg' }}" class="img-circle" alt="user-pic" width="48px">
        </a>
    </td>
<tr>

当帐户确实有个人资料照片 URL 时,它会正确显示。但是当没有个人资料照片时,默认的 URL 不会显示。

我做错了什么?

我正在使用 Laravel 5.1

你可以这样使用:

{{ isset($account->profile_pic_url) ? $account->profile_pic_url : '/profiles/anonymousUser.jpg' }}

代码:

@foreach ($accounts as $account)
<tr>
    <td class="user-image hidden-xs hidden-sm">
        <a href="#">
             <img src="{{ isset($account->profile_pic_url) ? $account->profile_pic_url : '/profiles/anonymousUser.jpg' }}" class="img-circle" alt="user-pic" width="48px">
        </a>
    </td>
<tr>

看了你的问题,我敢说你对 'or' blade 语法有点困惑。如 official documentation 中所述,'or' 是“Echoing Data If It Exists”的简洁快捷方式,但如果它不为 null 或为空(如我认为这是你的情况)...

例如,通常你会从数据库中获取模型,其中一些字段只是 EMPTY(''、0、false 等),这不是什么意思他们不存在。在这种情况下,'or' 语法将不适合您,因为它翻译成:

{{ isset($name) ? $name : 'Default' }}

...我认为您正在搜索类似的内容:

{{ (isset($name) && $name != '') ? $name : 'Default' }}

...或者如果您确实知道您正在评估的变量存在,只需(对于文本字段):

{{ ($name != '') ? $name : 'Default' }}