Reputation: 860
I come from the symfony (v1) world, where we had two types of partial rendering: partials, which loaded the same as:
@include('some.view')
and controllers, which would act the exact same way but would be ran with some controller logic behind hit. So, calling the same as above would first go to the matching some.view controller, and operate with the logic it had.
I'm trying to do the same with Laravel. Basically, I have this:
@foreach($array as $thing)
@include('controller.like.view', array('thing' => $thing))
@endforeach
... and I'd like my included view to run something like this (this is just an example, the actual code is a lot more complicated, otherwise I'd just write it with an if clause in Blade):
...
if ($thing%2) {
return 'a';
}
return 'b';
... so that only 'a' or 'b' would be printed in my loop. What's the best way to achieve this without having a bunch of PHP code in a Blade template?
Upvotes: 1
Views: 2185
Reputation: 152860
Why not just like that?
@foreach($array as $thing)
@if($thing%2)
a
@else
b
@endif
@endforeach
In general though, it's mostly a good way to prepare the data in your controller before passing it to the view. This way the view is just for presenting the data.
You could also write a little helper function or even a full class (with optional Facade for easy access) But it really depends on your needs
I'm not sure this is the best solution for you but it's the only one I can think of.
Put as much of the logic as you can in your "thing" class and then use that in the included view. Here's an example:
class Thing {
public function isA(){
// do the magic
return true;
}
}
View
@if($this->isA())
a
@else
b
@endif
Or to make a bit more like the controller from symfony you described:
class Thing {
public function getVars(){
// do stuff
return array(
'all' => 'the',
'vars' => 'you',
'need' => 'in',
'the' => 'view'
);
}
}
And then when you include the view
@include('item', $thing->getVars())
Upvotes: 1