Laravel Blade @yield variable scope

倾然丶 夕夏残阳落幕 提交于 2019-12-08 19:53:04

问题


I have two pages that are almost identical. One shows a list of users, the other shows the same list, but with more verbose information. So I am calling two views that extend the same wrapper. However, Laravel complains that $user is not defined in verbose.blade.php. I am passing $users to the view which seems to be available to content.blade.php but the $user that is created within the foreach loop doesn't seem to be accessible in verbose.blade.php.

verbose.blade.php

@extends('layout.content')

@section('user')
    {{ dd($user) }}
@endsection

nonverbose.blade.php

@extends('layout.content')

@section('user')
    {{ dd($user) }}
@endsection

content.blade.php

@extends('layout.app')

@section('content')
    @foreach($users as $user)
        @yield('user')
    @endforeach
@endsection

I have also tried @yield('user', ['user' => $user])

How would I go about making $user available in verbose.blade.php?


回答1:


Did you have tried to use @include?

@include('user', ['user' => $user])



回答2:


You get that error because of the order that Laravel parses blade templates in.

Sometimes we programmers get so engrained in our "don't repeat yourself (DRY)" principle that we take it too far. This is one of those times -- you should simply put the foreach loop directly into verbose.blade.php:

@extends('layout.app')

@section('content')
    @foreach($users as $user)
        @yield('user')
    @endforeach
@endsection


来源:https://stackoverflow.com/questions/31681465/laravel-blade-yield-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!