Laravel - 将变量传递给布局

我有一个布局,用于所有所谓的“部分”的每个循环。但是,每次我创建一个新的刀片文件并扩展该特定布局时,它都会不断地说该变量未定义。这是正确的,因为变量永远不会传递给布局文件。只有当我将变量传递给扩展布局的新刀片文件时,它才有效。如何在布局文件中使用该特定变量?


布局文件



<!doctype html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">


    <!-- CSRF Token -->

    <meta name="csrf-token" content="{{ csrf_token() }}">


    <title>{{ config('app.name', 'Laravel') }}</title>


    <!-- Scripts -->

    <script src="{{ asset('js/app.js') }}" defer></script>



    <!-- Fonts -->

    <link rel="dns-prefetch" href="//fonts.gstatic.com">

    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">


    <!-- Styles -->

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">

</head>

<body>

<div id="app">

    <div class="sidebar p-4 shadow-lg">

        <ul class="list-unstyled">

            <li class="sidebar-item"><a href="{{ route('sections') }}">Sections</a></li>

            @foreach($sections as $section)

                <li class="sidebar-item"><a href="">{{ $section->name }}</a></li>

            @endforeach

            <li class="sidebar-item"><a href="/">Go back home</a></li>

        </ul>

    </div>

    <div class="custom-container">

        @yield('content')

    </div>

</div>


<script type="text/javascript" src="{{ asset('js/jquery-3.4.1.min.js') }}"></script>

<script type="text/javascript" src="{{ asset('js/jquery-ui.min.js') }}"></script>

<script type="text/javascript" src="{{ asset('js/main.js') }}"></script>



</body>

</html>


服务提供者


<?php


namespace App\Providers;


use App\Section;

use Illuminate\Support\Facades\View;

use Illuminate\Support\ServiceProvider;


class ViewServiceProvider extends ServiceProvider

{

    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }

慕尼黑5688855
浏览 128回答 1
1回答

翻过高山走不出你

您可以使用 View Composer 在渲染时将专门需要的数据传递给布局。您可以在服务提供者的boot方法中定义它:use Illuminate\Support\Facades\View;public function boot(){&nbsp; &nbsp; View::composer('layout.yourlayout', function ($view) {&nbsp; &nbsp; &nbsp; &nbsp; $view->with('sections', ...);&nbsp; &nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP