Laravel - Modify and return variable from @include

て烟熏妆下的殇ゞ 提交于 2020-01-03 21:49:08

问题


I'm including multiple templates in a loop by using

@include('template.included')

Before including this template I define

$page = 0;

and inside the template, multiple times it calls

$page++;

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.

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?

Appreciate any suggestions!

EDIT:

My issue, for example:

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

I need $page to return 4, not 0


回答1:


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)

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.

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.



来源:https://stackoverflow.com/questions/30642235/laravel-modify-and-return-variable-from-include

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