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

Laravel Blade实现全局meta description及子页自定义描述方案

Laravel Blade 模板全局meta标签按需覆盖方案

你可以通过Blade自带的@yield默认值特性或者@hasSection判断实现需求,以下是具体操作步骤:

方法1:使用@yield默认值(最简方案)

直接修改布局文件index.blade里的meta description代码,将写死的content替换为带默认值的@yield语法:

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('site_title')</title>
    @yield('head_content')

    <!-- 替换原有写死的meta description -->
    <meta name="description" content="@yield('meta_description', 'This is the description')">
    ...
</head>

需要自定义meta的子页不用再往head_content里插完整标签,直接定义对应的section即可:

@extends('layouts.app')
<!-- 直接传自定义描述内容即可 -->
@section('meta_description', 'This is a different description')

如果子页没有定义meta_description这个section,Blade会自动使用@yield第二个参数的默认值,不会出现重复标签。

方法2:使用@hasSection判断(适合多分支复杂场景)

如果你的meta标签除了内容之外还有其他属性需要随子页调整,可以用判断逻辑实现:
布局文件代码:

@hasSection('meta_description')
    <!-- 子页有自定义时渲染子页的完整标签 -->
    @yield('meta_description')
@else
    <!-- 无自定义时渲染默认标签 -->
    <meta name="description" content="This is the description">
@endif

子页自定义时可以直接传完整标签:

@section('meta_description')
<meta name="description" content="This is a different description" data-custom-attr="xxx">
@endsection

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:57:01