Laravel Blade @yield variable scope

时间:2015-07-28 15:56:32

标签: laravel laravel-5 blade

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?

2 个答案:

答案 0 :(得分:2)

您是否尝试过使用@include?

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

答案 1 :(得分:0)

由于Laravel解析刀片模板的顺序,您会收到该错误。

有时候我们的程序员会在我们的“不要重复自己(DRY)”原则中深深扎根,我们认为它太过分了。这是其中一次 - 你应该简单地将foreach循环直接放入verbose.blade.php:

@extends('layout.app')

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