Nikita Nikita - 2 months ago 7
HTML Question

Laravel <title> in <body>

I mixed two examples from Laravel tutorial,and receive result, which I hope you help me to understand.
My route file is :

Route::get('/', function () {
return view('child', ['name' => 'Samantha']);


child.blade.php is

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>
@endsection
Hello, {{ $name }}.
@section('content')
<p>This is my body content.</p>
@endsection


And master.blade.php is

<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>

@section('sidebar')
This is the master sidebar.
@show

<div class="container">
@yield('content')
</div>
</body>
</html>


Output is

Hello, Samantha. This is the master sidebar. This is appended to the master sidebar. This is my body content.


Page source code is

Hello, Samantha.

<html>
<head>
<title>App Name - Page Title</title>
</head>
<body>

This is the master sidebar.


<p>This is appended to the master sidebar.</p>

<div class="container">
<p>This is my body content.</p>
</div>
</body>
</html>


Inspecting tool shows me empty
<head>
and
<title>
in
<body>
.

Why this happens with
Hello, {{ $name }}
and why inspecting tool lie to me about page body?

And、 if I put in @section
Hello, {{ $name }}
all will look fine.

Answer

As your child template extends layout, all data you have in it must be enclosed into a section

Hello, {{ $name }}. isn't in a section so it will be print at top of your output.

You can see extending template like a buffer. It starts taking contain of your child because it's the file you provide in your controller, then wrap it's content in sections defined in the layout.