2015-10-26 145 views
3

任何人都知道是否可以延长儿童刀片?Laravel刀片:@扩展(已扩展)的子刀片?

我的应用程序有一个公共布局模板,然后每个页面@extends。 每个页面可能会根据需要为其他HTML块包含一系列@includes(例如模态)。

@extends('common.layout') 

@section('content') 
    ... Some other content ... 
    @include('modals.modal-1') 
    @include('modals.modal-2') 
@endsection 

所有情态动词的有很多共同的样板代码(引导),所以我想要做的是什么定义一个主模型模板,都情态动词从@extend,然后@include那些在我的网页中按要求。所以/modals/modal-1.blade.php看起来是这样的:

@extends('common.modals') 

@section('modal-id', 'modal-1') 
@section('modal-title','Modal title') 

@section('modal-body') 
    ... Some HTML/Blade here ... 
@endsection 

每次我尝试虽然,生成的HTML已损坏。在上面的例子中,modal-1会显示两次,因为它首先出现,而modal-2根本不会出现。翻转订单和模态2将出现两次。

我想我可以简单地将我的模态主体放在一个变量中,并在@include语句@include('modal.blade', ['body' => '<div>...</div>'])中使用它,但使用@extends感觉更正确。

任何想法?

回答

0

我认为正确的方法包括模板,已经延伸其他一些模板是在你的包含的模板使用@overwrite代替@endsection

@extends('common.modals') 

@section('modal-id', 'modal-1') 
@overwrite 
@section('modal-title','Modal title') 
@overwrite 

@section('modal-body') 
    ... Some HTML/Blade here ... 
@overwrite 
3

你完全可以扩展从具有视图刀片视图已经延长。但是,您将模板继承与视图包含混合在一起,这会导致您的奇怪结果。

当使用@extend指令继承模板时,必须始终返回所需链上最低的子元素。假设您有3代模板:

//grandparent.blade.php 
<html> 
<head> 
    <title>My App</title> 
</head> 
<body> 
    @yield('parent-content') 
</body> 
</html> 

//parent.blade.php 
@extends('grandparent') 

@section('parent-content') 
<div class="container"> 
    @yield('child-content') 
</div> 
@endsection 

//child.blade.php 
@extends('parent') 

@section('child-content') 
<div class="page"> 
    //stuff 
</div> 
@endsection 

在这种情况下,您将返回子视图,并且它还包含上面的两代模板。但你可以永不返回parent.blade.php并期望它也返回该子视图。可能有100个子视图扩展父项,所以无法知道哪一个。

@include指令看作只是将您的视图中的HTML很好地分解为较小的位的方法。通常您会将其用于您想在多个视图中引用的可重复使用的代码段。尽管如此,它与模板继承不同。还要记住,包含的视图将获得与其父视图相同的所有数据(并且您甚至可以更多地传递它)。

就你而言,你必须决定什么构成页面的基础根。页面modal-1的核心是什么?如果是这样,您需要从您的控制器中返回modal-1作为子视图并将其扩展到链中。在这种情况下,请将文件完全保留在您的文章中。其父视图(common.modals)将需要更改为此:

@extends('common.layout') 

@section('content') 
    ... Some other content ... 

    @yield('modal-id') 
    @yield('modals-title') 
    @yield('modal-body') 

    @include('modals.modal-2') 
@endsection 

很明显,你会把每个地方它使在页面上感的产量报表。

但是,如果modal-1页面的核心,但只是一些额外的东西,你要包括(如部件),那么你就应该像你在父视图做include它。在这种情况下,您将需要从其中删除@extends指令,并且不必打扰在任何部分中包装主HTML。它只会被传递到视图中。如果您在包含的模板中包含部分,则必须在包含该部分的视图中屈服这些部分。因此,您的modal-1模板将显示为这样的样子:

<div> 
    <p>HTML goes here. No need to extend anything or wrap in a section. 
     You can still include {{$data}} though. 
    </p> 
</div> 

@section('script') 
    Including this section means that the view that is including this template 
    already contains a @yield('script') directive. 
    By including the @parent directive, this section will append that one. 

@parent 
@endsection