如何在模板中重用刀片部分

时间:2013-09-17 03:19:11

标签: laravel laravel-4 blade

我希望能够在视图中重复多次,每次重复都有不同的内容。

部分是一个简单的面板,带有标题和一些内容。每个面板中的内容的复杂程度各不相同,因此我希望能够使用@section('content')方法传递数据。

我的设置如下:

panel.blade.php - 要重复的部分。

<div class="panel">
    <header>
        @yield('heading')
    </header>
    <div class="inner">
        @yield('inner')
    </div>
</div>

view.blade.php - 重复部分的视图

@extends('default')

@section('content')

    {{-- First Panel --}}
    @section('heading')
        Welcome, {{ $user->name }}
    @stop
    @section('inner')
        <p>Welcome to the site.</p>
    @stop
    @include('panel')

    {{-- Second Panel --}}
    @section('heading')
        Your Friends
    @stop
    @section('inner')
        <ul>
        @foreach($user->friends as $friend)
            <li>{{ $friend->name }}</li>
        @endforeach
        </ul>
    @stop
    @include('panel')

@stop

我遇到了与此问题相同的问题:http://forums.laravel.io/viewtopic.php?id=3497

第一个面板按预期显示,但第二个面板只是重复第一个面板。

我该如何纠正?如果这是一个不好的方法来完成这个,那会是一个更好的方法吗?

1 个答案:

答案 0 :(得分:14)

对于Laravel 5.4,Components & Slots可能对您有用。以下解决方案适用于Laravel 4.x,并且可能&lt; = 5.3。


在我看来,这是@include语法的一个愚蠢的用例。您正在保存的HTML重新输入的数量可以忽略不计,尤其是因为其唯一可能复杂的部分是inner内容。请记住,需要完成的解析越多,应用程序的开销也越大。

另外,我不知道@yield&amp;的内部运作方式。 @section功能,所以我无法说出以这种方式工作的“正确”。包括通常使用密钥=&gt;值对作为include调用中的参数传递:

@include('panel', ['heading' => 'Welcome', 'inner' => '<p>Some stuff here.</p>'])

不是打包大量HTML的最理想的地方,但这是“设计”的方式(据我所知,至少)。

那说......

使用模板文档页面的"Other Control Structures"部分中提到的@section ... @overwrite语法。

@extends('default')

@section('content')

    {{-- First Panel --}}
    @section('heading')
        Welcome, {{ $user->name }}
    @overwrite
    @section('inner')
        <p>Welcome to the site.</p>
    @overwrite
    @include('panel')

    {{-- Second Panel --}}
    @section('heading')
        Your Friends
    @overwrite
    @section('inner')
        <ul>
        @foreach($user->friends as $friend)
            <li>{{ $friend->name }}</li>
        @endforeach
        </ul>
    @overwrite
    @include('panel')

@stop
相关问题