Laravel Blade,子页面的全局元描述和不同的元描述

Laravel Blade, global meta description and different meta description for subpage

我有一个 index.blade,在 header 中包含所有必要的元标记,让我们以描述为例:

<meta name="description" content="This is the description">

这是我当前的索引文件

<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 name="description" content="This is the description">
    ...
</head>

现在,对于特定的子页面 (/page),我想要一个不同的描述,这就是我所拥有的:

@extends('layouts.app')
@section('head_content')

<meta name="description" content="This is a different description">

@endsection

不幸的是,这在最后的 html 子页面上添加了两个元描述。有没有办法让单个子页面有不同的元描述,但除此之外还有全局描述?

您可以使用@overwrite代替@endsection来...覆盖原来的内容:

@extends('layouts.app')
@section('head_content')
<meta name="description" content="This is a different description">
@overwrite

编辑:更改您的布局以使用部分而不是 @yield:

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

第二次编辑: 如果你有多个元标签,你也可以在你的布局中使用这样的东西:

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('site_title')</title>
    <meta name="description" content="@yield('meta_description', 'This is the description')">
    <meta name="keywords" content="@yield('meta_keywords', 'these,are,the,keywords')">
    ...
</head>

然后在您的子页面中您可以使用:

@extends('layouts.app')
@section('meta_description', 'A subpage description');
@section('meta_keywords', 'my,subpage,keywords');

@overwrite@endsection 相同,但替换现有内容

@extends('layouts.app')
@section('head_content')
<meta name="description" content="This is a different description">
@overwrite

DOCUMENTATION