【问题标题】:How to reuse a blade partial in a template如何在模板中重用刀片部分
【发布时间】:2013-09-21 08:32:40
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: laravel laravel-4 blade


    【解决方案1】:

    对于 Laravel 5.4,Components & Slots 可能对你有用。以下解决方案适用于 Laravel 4.x,也可能是


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

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

    @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
    

    【讨论】:

    • 这里应该指出的一点是; “@include”指令必须在您的面板部分指令下方。就像上面的例子一样。如果你把'@include' 放在'@section' 指令之上,它不会对多个'@includes' 起作用。同样,如果您使用“@stop”,它将仅适用于一个面板。对于多个面板;你应该使用'@overwrite'。上面的例子是正确的,我只是指出一些重要的事情。
    猜你喜欢
    • 2016-12-18
    • 2014-09-04
    • 2013-08-16
    • 2014-11-13
    • 2016-05-25
    • 2018-09-25
    • 1970-01-01
    • 2014-03-01
    • 2016-07-04
    相关资源
    最近更新 更多