Best way to generate page titles?

Published 10 months ago by Boubou

Hello,

I would like to know what is the best way of generating page titles in Laravel please. I understand how to do it in pure PHP but with Laravel I am a bit lost.

For example, you have a main layout file, inside the layout file you have partials, if a partial shows content "XYZ" and that in this content I have already a field "title", how can I pass this $data->title that may come from multiple controllers to the main layout file, this is the part that confuses me.

I hope I explain it correctly:-)

Thanks!

Swaz
Swaz
10 months ago (57,965 XP)

You can pass variables to the parent like this:

about.blade.php

@extends('layout', ['title' => 'About'])
@section('content')
    <h1>About</h1>
@endsection

layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>
        @isset($title)
            {{ $title }} | 
        @endisset
        {{ config('app.name') }}
    </title>
</head>
<body>
    @yield('content')
</body>
</html>
Boubou

Thanks Swaz, I will give it a try

wilk_randall

IMO it's cleaner to yield a section called 'title' in your main layout blade.

layout.blade.php


<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'some default title to show if child doesnt set one')</title>
</head>
<body>
    @yield('content')
</body>
</html>

test.blade.php


@extends('layout.blade.php')
@section('title', 'Test Page')

@section('content')
    <h1>Test Page</h1>
@endsection

Snapey
Snapey
10 months ago (1,036,815 XP)

As ever there are many different ways. I use view()->share('siteTitle','the title for this page') in the controller and then in the master layout;

    <title>{{ $siteTitle or 'SpeakerNet' }}</title>

There's no 'correct' answer

martinbean

@Boubou I just define a section called title in my master layout, that defaults to the site name:

<!-- /resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
  <head>
    <title>@yield('title', config('app.name'))</title>
  </head>
</html>

I can then set it in Blade templates that extend this template:

<!-- /resources/views/home.blade.php -->
@extends('layouts.app')

@section('title', 'Home')
bestmomo

Another way I use to get some automatism :

I have a config for titles based on routes names :

<?php

return [

    'admin' => 'dashboard',
    'users' => [
        'index' => 'usersGestion',
        'edit' => 'userEdit',
    ],

   ...

And lang files for translations :

<?php

    'titles' => [
        'dashboard' => 'Dashboard',
        'usersGestion' => 'Users Gestion',
        'userEdit' => 'User Edition',
        'contactsGestion' => 'Contacts Gestion',

    ...

Then in a view composer :

$title = config('titles.' . Route::currentRouteName());
$title = __('admin.titles.' . $title);

$view->with(compact('title', '...));

So in layout just set :

{{ $title }}

And it works :)

Please sign in or create an account to participate in this conversation.