douchun5969 2016-01-22 04:13
浏览 47
已采纳

如何在环路内屈服时纠正Laravel的Blade变量部分范围?

When I include a blade template that extends a base blade, any variables within the section of the included blade show only the variables of the first iteration.

Reading around it seems the render order here is important, and views are rendered before variables, or vice versa.

Note

  • I have read this SO question/answer: Laravel Blade @yield variable scope
  • The below snippet is greatly reduced in complexity, so the example could be restructured to exclude sections/extends. However my real case can't be

Example

// index.blade.php
//
@foreach($jobs as $job)
    {{ $job->id }} // <-- Correct output, 1,2,3,..N
    @include('job-detail', ['id' => $job->id])
@endforeach

Then in the job detail blade

// job-detail.blade.php
//
@extends('job-base')

A: {{ $id }} // <-- Correct output, 1,2,3,..N

@section('content')
    B: {{ $id }} // <-- Incorrect output, 1,1,1,..1 (or whatever the first index is)
@endsection // have also tried @stop

Then in the job base blade

// job-base.blade.php
//
@yield('content') // Have also tried @section('content') + @show
  • 写回答

1条回答 默认 最新

  • douou1891 2016-01-22 05:30
    关注

    After wading through the source code, namely BladeCompiler and View/Factory I noticed the following snippet:

    protected function compileOverwrite($expression)
    {
        return '<?php $__env->stopSection(true); ?>';
    }
    

    In the background Laravel appears to store rendered content (by including the file, and extract current variables in a ob_style fashion) in a keyed array, with the view name being the key.

    When stopSection is not passed a boolean true, it creates a new key, and the view gets the data from the original key.

    Long story short, it's now undocumented (for 5.1+) but can be found in the docs for 5.0: https://laravel.com/docs/5.0/templates

    However it doesn't really explain the "why". This page seems to explain it a little better:

    http://laravel-recipes.com/recipes/244/stopping-injecting-content-into-a-section-and-overwriting

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据