Added variable inside nested views

As part of laravel, I have several nested views, as shown below.

<mainview> loop @include <sub-view> loop @include <sub-sub-view> 

I would like to keep a counter of how many sub-sub-views there are. It becomes, in fact, a string counter. I'm not sure where to declare / initialize this variable ($ sub-sub-view-counter) and where to increase it along the way. No matter where I place it, it cannot be seen and enlarged for each species.

+4
source share
1 answer

It might be a little hack, but if nothing better appears ...

You will need either a helper function or an object (the easiest way is to put this in the model). For demonstration, I chose the option of the object, since I think that it is a little easier to use and, more importantly, the easiest way to satisfy your needs. It also implicitly supports multiple counters, as the value is stored for each object (you need to jump over several hoops to get this functionality using the function).

 class Counter { private $count = 0; public function inc() { return ++$this->count; } } 

So, for this particular implementation, you will need to create it somewhere. You can put a line like this in the parent view somewhere before including your subviews, or enter it with PHP using the with() method.

 <?php $counter = new Counter(); ?> 

You enable the subtask as usual (remember to use include , not render , to save the $counter variable). I used the for loop for testing, but you can, of course, use any option you want.

 @for($i=0; $i<10; $i++) @include('home.sub') @endfor 

And finally, you can just call it in a subview

 <span>{{ $counter->inc() }}</span> 

You can easily extend this model with the factory to get counter values โ€‹โ€‹from anywhere in the application, but for your use case this basic option should be enough.

+1
source

All Articles