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

Laravel Blade模板引入头部报‘Undefined variable $slot’错误求助

解决Laravel Blade「Undefined variable $slot」错误

错误原因

$slot是Blade组件专属变量,用于传递组件包裹的动态内容。出现这个错误通常是两种情况:

  • 你的header.blade.php模板中使用了$slot,但用普通的@include引入(@include不会自动传递$slot变量);
  • 使用@component引入组件时,模板未给$slot设置默认值,且未传递任何内容。

解决方案

情况1:头部是静态公共模板(无需动态内容)

如果header只是固定的导航、logo等静态内容,直接移除模板中的$slot代码,用@include引入即可:

header.blade.php

<header>
    <nav>
        <a href="/">首页</a>
        <a href="/about">关于我们</a>
    </nav>
</header>

子模板/主模板中引入

@include('header')

情况2:头部是需要传递动态内容的组件

如果需要给头部传递自定义内容,需给$slot设置默认值,避免未定义错误:

header.blade.php

<header>
    <!-- 给$slot设置空默认值 -->
    {{ $slot ?? '' }}
    <nav>
        <!-- 固定导航内容 -->
    </nav>
</header>

引入方式:

  • 使用@component(Laravel 7之前):
@component('header')
    <!-- 这里可以写要传递给$slot的内容,比如自定义标题 -->
    <h1>自定义页面头部标题</h1>
@endcomponent
  • 使用Laravel 7+推荐的组件语法:
<x-header>
    <h1>自定义页面头部标题</h1>
</x-header>

如果不需要传递内容,直接写<x-header></x-header>即可,默认值会生效。

规范模板层级(更推荐)

通常把头部、底部放在主布局模板中,子模板通过扩展主模板来复用,避免重复引入:

主布局模板 layouts/app.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    @include('header')
    <main>
        @yield('content')
    </main>
    @include('footer')
</body>
</html>

子模板

@extends('layouts.app')

@section('title', '首页')

@section('content')
    <h1>欢迎访问首页</h1>
@endsection

这种方式下,子模板无需手动引入头部,直接填充内容区块即可,彻底避免变量冲突问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:58:31