You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键修改点

  1. 补充@endif闭合@if条件判断,解决语法错误;
  2. 将“no posts for you”提示移到@forelse的@empty分支下,仅当用户无任何帖子时显示,符合需求逻辑;
  3. 移除多余的@else分支,避免重复提示。

内容的提问来源于stack exchange,提问作者sunset-crow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:25:32