【问题标题】:Laravel Blade, global meta description and different meta description for subpageLaravel Blade,全局元描述和子页面的不同元描述
【发布时间】:2021-10-31 05:06:19
【问题描述】:

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

<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 子页面上添加了两个元描述。有没有办法让单个子页面有不同的元描述,但有全局描述?

【问题讨论】:

    标签: php laravel laravel-blade meta-tags


    【解决方案1】:

    您可以使用@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');
    

    【讨论】:

    • 嘿@brombeer,感谢您的快速回答。不幸的是,它仍然在最后的子页面上向我显示了两个元描述。如果有帮助,我用我的索引文件的样子更新了我的答案。谢谢! :)
    • 由于您的布局/索引中的&lt;meta&gt; 元素不在@section 内,因此它无法被替换并且将始终呈现。我更新了我的答案,看看当您更改索引以使用某个部分时它是否有效
    • 感谢您的更新,这似乎有效。所以基本上我必须将 all 我的元标记放在索引文件中的 @section(head_content@show 之间,然后在子页面中覆盖它。
    • @Paranoia 不一定。我使用带有默认值的@yield 的第二次编辑编辑了我的答案,看看这是否适用于多个元元素
    • 请每个“问题”一个问题。如果此答案解决了您当前的问题,请接受它,以便将其标记为已解决。这应该与 OG 属性以相同的方式工作。尝试使用 opengraph 属性实现这两种方式之一,如果您有问题,请提出另一个问题。谢谢,很高兴它有效
    【解决方案2】:

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

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

    DOCUMENTATION

    【讨论】:

    • 如果对您有帮助,请标记为已验证谢谢@Paranoia
    • 嘿@vikas,也感谢您的快速回答!不幸的是,它仍然在最后的子页面上向我显示了两个元描述。如果有帮助,我用我的索引文件的样子更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2012-05-16
    • 2022-01-22
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多