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

Laravel中向已引入视图的@stack推送内容无显示问题求助

解决Blade模板@push内容无法显示的问题

问题根源

你遇到的问题是Blade模板渲染顺序导致的:当default.blade.php中用@include('main.includes.header')加载头部视图时,header.blade.php里的@stack('user_navbar')会被立即解析并渲染输出。而你写在@include之后的@push('user_navbar'),是在stack已经渲染完成后才执行的,所以推送的内容无法被追加到已经生成的stack中。


解决方法

方法1:调整@push的位置(最简单直接)

把@push('user_navbar')代码块移到@include('main.includes.header')的前面,这样推送的内容会在stack渲染前被Blade收集,就能正常显示了。

修改后的default.blade.php代码:

@push('user_navbar')
    The user Navbar is here 
@endpush

@include('main.includes.header')
    
@yield('content')
@include('main.includes.footer')

方法2:用@yield替代@stack(适合需要默认内容的场景)

如果需要给导航栏设置默认内容,或者允许子视图覆盖/追加内容,可以把header.blade.php中的@stack改成@yield:

修改header.blade.php:

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    SomeThings come here
</head>
<body>

@yield('user_navbar')

然后在default.blade.php中用@section定义导航栏内容:

@include('main.includes.header')

@section('user_navbar')
    The user Navbar is here 
@endsection
    
@yield('content')
@include('main.includes.footer')

如果需要子视图追加内容到导航栏,可以在子视图中使用@parent:

@section('user_navbar')
    @parent
    追加的导航内容
@endsection

方法3:使用Blade组件(现代Laravel推荐写法)

把头部视图重构为Blade组件,通过插槽(Slot)传递导航栏内容,灵活性更强。

  1. 创建resources/views/components/header.blade.php组件文件:
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    SomeThings come here
</head>
<body>

{{ $userNavbar }}
  1. 在default.blade.php中使用组件并传递插槽内容:
<x-header>
    @slot('userNavbar')
        The user Navbar is here 
    @endslot
</x-header>
    
@yield('content')
@include('main.includes.footer')

内容的提问来源于stack exchange,提问作者Ahmad Badpey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:43:09