Search code examples
phplaravellaravel-blademeta-tags

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


I have a index.blade with all the necessary meta tags in the header, lets take the description for example:

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

This is my current index file

<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>

Now, for a specific subpage (/page), I would like to have a different description, this is what I have:

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

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

@endsection

This unfortunately adds both meta description on the final html subpage. Is there a way to have a different meta descriptions for a single subpage, but otherwise have the global description?


Solution

  • You can use @overwrite instead of @endsection to ... overwrite the original content:

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

    Edit: change your layout to use a section instead of @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>
    

    2nd Edit: If you have multiple meta tags you could also use something like this in your layout:

    <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>
    

    Then in your subpage you could use:

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