在尝试输出文件之前,我想检查资产 {{ asset }} 是否存在。
经过一些谷歌搜索后,我尝试了一些方法,但似乎在Laravel 5.0上都不起作用。
以下是我在前端刀片视图中想象的请求示例:
@if(asset(path-to-asset))
<img src="image-path"/>
@else
<img src="no-image-path"/>
@endif
感谢
在尝试输出文件之前,我想检查资产 {{ asset }} 是否存在。
经过一些谷歌搜索后,我尝试了一些方法,但似乎在Laravel 5.0上都不起作用。
以下是我在前端刀片视图中想象的请求示例:
@if(asset(path-to-asset))
<img src="image-path"/>
@else
<img src="no-image-path"/>
@endif
感谢
最好从 Web 服务器处理这个问题,因为仅仅因为文件存在,并不意味着它对公共网络是可访问的。这也意味着你不需要在各处重复代码来检查文件是否存在。具体请参见:使用404图片替换无效的图像URL
不过,这也可以通过 PHP 实现。
@if (file_exists(public_path('path/to/asset.png')))
<img src="{{ asset('path/to/asset.png') }}">
@else
<img src="{{ asset('path/to/missing.png') }}">
@endif
除了使用本地的php
方法这里,你还可以使用:
if (File::exists($myfile)){ ... }
然而,需要注意的是asset(...)
会返回资源的绝对URL,但你需要在文件系统中检查它是否存在,因此你需要像下面这样的路径:
$img = path('public').'/path/to/image.png';
<?php
$image = parse_url($user->image);
if(isset($image['host'])){
$image= $user->image;
}
else if($image==null){
$image= Request::root().'/uploads'.'/subsystems_icons/'.'democp.jpg';
}
else {
$image= Request::root().'/uploads/'.$user->image;
}
?>
<div class="">
<img class="image" style="width: 100%; height: 300px; object-fit: contain ;"
src="{{$image}}">
</div>