Laravel-修改并从@include返回变量 [英] Laravel - Modify and return variable from @include

查看:45
本文介绍了Laravel-修改并从@include返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用循环包含多个模板

I'm including multiple templates in a loop by using

@include('template.included')

在定义此模板之前,先定义

Before including this template I define

$page = 0;

并在模板中多次调用

$page++;

在所包含的模板内部,该值正确递增,但是在模板外部,似乎$ page变量保持不变-好像@include创建了您使用的每个var的副本.

Inside the included template, the value correctly increments, however outside the template it seems like the $page variable stays the same - it's looking like @include creates it's own copy of each var you use.

我需要此$ page变量从这些模板内部进行更新,并将其值返回给我的主模板-我错过了一些简单的东西吗?

I need this $page variable to update from inside those templates, and have it's value returned back to my main template - am I missing something simple?

感谢任何建议!

我的问题,例如:

$page = 0;
@include('template.included') //This calls $page++ 5 times
echo $page; //returns 0

我需要$ page返回4,而不是0

I need $page to return 4, not 0

推荐答案

您的假设是正确的,Laravel的视图系统确实会为其加载的每个视图创建一个新范围. Illuminate\View\Factory::make() 方法包含视图时使用的是这样做的:

Your assumption is correct, Laravel's view system does creates a new scope for each view it loads. The Illuminate\View\Factory::make() method which is used when including views, does this:

new View($this, $this->getEngineFromPath($path), $view, $path, $data)

它正在创建一个新视图并将数据传递给它,这实际上意味着它正在发送信息的副本.由于自变量,没有通过引用传递(已弃用,并且在更新的版本中PHP版本已被删除),您无法完成的操作.

It's creating a new view and passing the data to it, which effectively means it's sending a copy of the information. Since arguments there are not passed by reference (which was deprecated and in newer PHP versions is already removed), what you want can't be done.

话虽如此,您的方法似乎有缺陷.在我看来,您好像正在构建视图中的分页,这是您不应该在此处执行的操作. Laravel已经提供了一种非常简单的方法来创建分页,您也许应该研究一下.

That being said, your approach seems flawed. It looks to me like you're building the pagination in the view, which is something you should not be doing there. Laravel already offers a very easy way to create Pagination, you should perhaps look into that.

这篇关于Laravel-修改并从@include返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆