如何在 Blade 模板中包含子视图?

我试图建立一个网站使用 laravel,但我真的有麻烦,基本的东西,文档只是没有涵盖。

在本例中,我看到它说我可以使用 @include('view.name')在另一个视图中包含一个视图。什么是 view.name?它被保存在哪里?我尝试创建一个文件 app/views/view.name.blade.php,但它没有被读取。文件名如何映射到刀片服务器名称?

201144 次浏览

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
<html stuff>
@yield('content')
</html>

file: hello.blade.php

@extends('layout')


@section('content')
<html stuff>
@stop

You can use the blade template engine:

@include('view.name')

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php


// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php


// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php


// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>\{\{$paramName}}</p>

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
@include('parentFolder.childFolder.mypage')
</html>

One more interesting situation with directory structure in laravel, following up on @gwed great answer:

@include('hello.world');

would display the following view:

// for laravel 5.X
resources/views/hello/world/index.blade.php