How to reuse a blade partial in a template

后端 未结 1 1090
别跟我提以往
别跟我提以往 2021-02-20 03:50

I would like to be able to repeat a partial a number of times within a view, with different content in each repetition.

The partial is a simple panel, with a heading, an

相关标签:
1条回答
  • 2021-02-20 04:33

    For Laravel 5.4, Components & Slots may be useful for you. The following solution is for Laravel 4.x, and likely <= 5.3 as well.


    In my opinion, this is a silly use case for the @include syntax. The amount of HTML retyping you're saving is negligible, especially since the only potentially-complicated part of it is the inner content. Keep in mind, the more parsing that needs to be done, the more overhead your application has, also.

    Also, I don't know the inner workings of the @yield & @section features, so I can't say how "proper" it is to work your includes this way. Includes typically utilize a key => value pair passed as a parameter in the include call:

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

    Not the most ideal place to pack a bunch of HTML, but that's the "designed" way (as far as I know, at least).

    That said...

    Use the @section ... @overwrite syntax mentioned in the "Other Control Structures" part of the template docs page.

    @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
    
    0 讨论(0)
提交回复
热议问题