Blade模板语法错误:forelse内嵌@if后触发unexpected end of file
问题分析与解决
语法错误根源
你的Blade模板出现syntax error, unexpected end of file是因为嵌套的@if语句未闭合:在@forelse循环内使用了@if和@else,但缺少@endif来结束条件判断,导致模板引擎解析时无法匹配标签结构。
逻辑优化建议
原代码逻辑存在问题:当前每遇到一个不属于当前用户的帖子,就会显示一次“no posts for you”,这不符合“仅显示自己的帖子,无帖子时提示”的需求。正确逻辑应为:遍历帖子时只渲染当前用户的内容,当用户没有任何帖子时,统一显示提示。
修正后的完整代码
@extends('master') @section('header-intro') @endsection @section('main') <div class="container"> <!--Section: Content--> <section class="text-center"> <div class="posts"> @forelse ($posts as $post) @if (auth()->user()->id === $post->user->id) <div class="post"> <div class="card"> <div class="bg-image hover-overlay ripple" data-mdb-ripple-color="light"> <img src="{{ asset('storage/') . '/' . $post->thumb }}" class="img-post" /> <a href="#!"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div> </a> </div> <div class="card-body"> <h5 class="card-title">{{ $post->title }}</h5> <p class="card-text"> {{ Str::limit($post->body, 58, '...') }} </p> <p>Autor: {{ $post->user->name }} - has {{ $post->comments->count() }} comments</p> <a href="{{ route('post', $post->slug) }}" class="btn btn-primary">read more</a> </div> </div> </div> @endif @empty <h4>no posts for you</h4> @endforelse </div> @if (request()->input('search')) {{ $posts->appends(['search' => request()->input('search')])->links() }} @endif </section> </div> @endsection
关键修改点
- 补充
@endif闭合@if条件判断,解决语法错误; - 将“no posts for you”提示移到
@forelse的@empty分支下,仅当用户无任何帖子时显示,符合需求逻辑; - 移除多余的
@else分支,避免重复提示。
内容的提问来源于stack exchange,提问作者sunset-crow
相关产品推荐
相关产品推荐

