【问题标题】:How to correct Laravel's Blade variable section scoping when yielding inside a loop?在循环内产生时如何更正 Laravel 的 Blade 可变部分范围?
【发布时间】:2016-01-22 13:30:16
【问题描述】:

当我包含一个扩展基本刀片的刀片模板时,包含刀片部分中的任何变量都只显示第一次迭代的变量。

仔细阅读,这里的渲染顺序似乎很重要,视图在变量之前渲染,反之亦然。

注意

  • 我已阅读此 SO 问题/答案:Laravel Blade @yield variable scope
  • 以下 sn-p 的复杂性大大降低,因此可以重新构建示例以排除节/扩展。但是我的真实情况不可能

示例

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

然后在作业详细信息刀片中

// 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

然后在作业基础刀片中

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

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.1


    【解决方案1】:

    在翻阅源代码后,即BladeCompilerView/Factory我注意到以下sn-p:

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

    在后台,Laravel 似乎将渲染的内容(通过包含文件,并以 ob_style 方式提取当前变量)存储在键控数组中,视图名称是键。

    当 stopSection 没有传递一个布尔值 true 时,它​​会创建一个新键,视图从原始键中获取数据。

    长话短说,它现在没有文档记录(对于 5.1+),但可以在 5.0 的文档中找到: https://laravel.com/docs/5.0/templates

    但它并没有真正解释“为什么”。这个页面似乎解释得更好一点:

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

    【讨论】:

    • 所以 TL;DR 版本以 @section 开头并以 @overwrite 结尾。你是上帝。谢谢你拯救了我的幸福。
    猜你喜欢
    • 2017-01-07
    • 2015-10-19
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2023-03-04
    • 2016-01-24
    相关资源
    最近更新 更多