12

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

部分是一个简单的面板,带有标题和一些内容。每个面板中的内容可能复杂程度不同,所以我希望能够使用@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

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

我该如何纠正?如果这是完成这项工作的糟糕方法,那么更好的方法是什么?

4

1 回答 1

14

对于 Laravel 5.4,组件和插槽可能对您有用。以下解决方案适用于 Laravel 4.x,也可能 <= 5.3。


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

另外,我不知道@yield&@section功能的内部工作原理,所以我不能说以这种方式工作你的包含有多“合适”。包含通常利用在包含调用中作为参数传递的键 => 值对:

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

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

那就是说...

使用模板文档页面的“其他控制结构”部分中@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
于 2013-09-17T06:15:52.310 回答