Laravel - set meta tag dynamically with @section

2019-07-08 10:33发布

问题:

i would like implement facebook share button function whereby it will capture the meta tags information during user hit the share button.

I've a head.blade.php that include some meta tag to be captured. Example

<meta property="og:url" content="@yield('facebook_share_url')">
<meta property="og:image" content="@yield('facebook_share_image')">
<meta property="og:description" content="@yield('facebook_share_description')">

And i have a default.blade.php.

<!doctype html>
<html>
<head>
    @include('includes.head')
</head>
<body>
<div class="container">

    <header class="row">
        @include('includes.header')
    </header>

    <div id="main" class="row">
        @yield('content')
    </div>
</div>

@include('includes.footer')
</body>
</html>

So when i browse to some url says www.example.com/details, the default.blade.php will yield the content from this details.blade. And at this moment i would like to change the facebook meta tag properties, so i did something like below in details page.

@section('facebook_share_image', 'This is a description')
@section('facebook_share_description', 'This is an individual page title')

The code work fine but i would like to render it from my view data. Something like @section('facebook_share_description', {{ $data->description }})

but when i check my meta tag, it gives me nothing. Is it possible to do so?

回答1:

I am not sure whether this is what you want or what you are looking for, but why not try placing the meta tags in the default.blade.php only instead of placing it in a partial.

For example, insert in head tag of default.blade.php:

@yield('facebook_meta')

view_file.blade.php

@section('facebook_meta')
    <meta property="og:url" content="Place your data here">
    <meta property="og:image" content="Place your data here">
    <meta property="og:description" content="Place your data here">
@endsection

The above approach works much better, according to me.

Maybe this can help you out.