我正在用Laravel做这个项目。
根据我正在观看的教程,我必须在主视图的顶部添加这段代码。
@extends('layouts.masters.main')
因为我是新的Laravel这让我想知道为什么我不能简单地使用。
@include('layouts.masters.main')
我尝试了一下,它基本上做了同样的事情。唯一的问题是,我知道include是如何工作的,但我不知道extends是如何工作的。有什么区别吗?是什么?为什么教程的人选择@extends
而不是@include.
@include
就像一个基本的PHP include,它包含了一个"partial"视图到你的视图。
@extends
允许你"扩展"一个模板,它定义了自己的章节等。您可以扩展的模板将使用@yield
定义自己的部分,然后您可以将自己的内容放入视图文件中。
的例子:
template.blade.php
<html>
<body>
@yield('header')
@yield('content')
@yield('footer')
</body>
</html>
view-one.blade.php
@extends('template')
@section('header')
View one's header
@endsection
@section('content')
View one's content
@endsection
@section('footer')
View one's footer
@endsection
这将导致:
<html>
<body>
View one's header
View one's content
View one's footer
</body>
</html>
现在您可以创建另一个视图,它扩展了相同的模板,但提供了自己的部分。
使用@extend
的另一个好处是继承。您可以提供一个基本模板,然后提供另一个扩展该模板的子模板,该子模板随后产生自己的部分。然后您可以扩展该子模板。
@include
不提供使用@extend扩展布局模板所提供的结构骨架。使用@include
,您将插入来自另一个文件的部分。
扩展刀片模板为布局模板中定义的视图提供了一个结构。例如,布局:
布局/layout.blade.php
<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8" /><title>DOCUMENT</title></head>
<body>
@yield('header')
@yield('content_1')
@yield('content_2')
@yield('content_3')
@yield('footer')
</body>
</html>
与视图
show.blade.php
@extends('layouts.layout')
@section('content_1')
<h2>Content1 Puppy Dog</h2>
@endsection
@section('footer')
<h1>I wanna be at the bottom</h1>
@endsection
@section ('content_3')
<h2>Content3 Horsie</h2>
@endsection
@section ('content_2')
<h2>Content2 Kitty Cat</h2>
@endsection
@section('header')
<h1>I wanna be at the top</h1>
@endsection
给出输出:
<body>
<h1>I wanna be at the top</h1>
<h2>Content1 Puppy Dog</h2>
<h2>Content2 Kitty Cat</h2>
<h2>Content3 Horsie</h2>
<h1>I wanna be at the bottom</h1>
</body>
@extends
与@section
是更强大和方便的方式使用布局(s),特别是在较大的应用程序。它允许使用继承。你可以对多个@include
做同样的事情,但它会降低可读性和可维护性。
点击这里阅读更多关于@extends
及其工作原理的信息