Search code examples
htmllaravel-5meta-tagslaravel-blade

Inject meta tags per page


So I run a Laravel 5.4 project and we have a system whereby each page would require separate META tags to correctly show when people tweet urls etc. So my question:

How do I go about injecting the below code into my head tags?

e.g. A new article might look like this:

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@mysite">
<meta name="twitter:title" content="News Article - Donald Trumps Twitter Deleted!">
<meta name="twitter:image" content="imageurl">
<meta name="twitter:description" content="Donald Trump lost access to his twitter for...">
<meta name="twitter:domain" content="https://www.example.com">
<meta name="description" content="Donald Trump lost access to his twitter for..."/>
<meta name="keywords" content="News, Donald, Trump, Media, Reporting, Urgent, Breaking, Twitter"/>

.

Whereas something for say a forum post would look like this:

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@mysite">
<meta name="twitter:title" content="Forum - Welcome to the forum!">
<meta name="twitter:image" content="imageurl">
<meta name="twitter:description" content="Hey there and welcome to our forum! For the chance to win $250 please...">
<meta name="twitter:domain" content="https://www.example.com">
<meta name="description" content="Hey there and welcome to our forum! For the chance to win $250 please..."/>
<meta name="keywords" content="Forum, Thread, Post, Win, Welcome, Twitter"/>

.

So, how? I'm so confused having spent an hour goolging this one!


Solution

  • Checkout the laravel docs about Template Inheritance (https://laravel.com/docs/5.2/blade#template-inheritance)

    You can than inject the meta data into your <head></head> by using @section('title',$article->title) in your blade

    Example of your situation:

    <head>
        <meta name="twitter:title" content="@yield('twitter_title')">
        <meta name="twitter:image" content="@yield('twitter_image')">
    </head>
    

    In your blade:

    @extends('layouts.layout') //This loads the default blade with your <head></head> section
    
    @section('twitter_title',$article->title)
    @section('twitter_image',$article->image)