Laravel Blade Recursive Partials with @each

Originally published at:

In this tutorial, we’ll go through the process of implementing recursive partials in Laravel’s Blade templating engine by means of the @each command. This will allow us to render data structures with an arbitrary number of nested children without needing to know the maximum depth of the array.

The Data

The data I’m talking about is data like folder structures which can go deep into many levels. For our case, let’s imagine we’re dealing with a predefined data set of “Projects” in a todo application like Todoist. Feel free to grab the sample data from this gist or the code embed below:

Continue reading this article on SitePoint

Interesting, but how would you deal with the “ul” tags?
I suppose they would be just dropped in your example, or is there a way to have a pre/post string/variable output by “@each”?

Unfortunately, the partial doesn’t lend itself to the each approach due to this, indeed. Extending this helper, though, is an option - perhaps an additional parameter like $wrappingElement would be useful.

Is it possible to pass variables to the empty partial? Like so:

@each('_macros/document', $document, 'document', '_macros/document-empty', ['label' => 'Doc Label'])

“…perhaps an additional parameter like $wrappingElement would be useful…”

This reminds me of Zend Frameworks form decorators and extra complexity needed when you want something slightly custom. Unfortunately, templating libraries like Blade add overhead where there wouldn’t otherwise be in many cases.

themccallister’s question is a good illustration of the unnecessary overhead. You end up fiddling around with basic functionality instead of solving the problems you want to solve.

It’s not possible, no, not without tweaking the helper.

Yes, intimately familiar with that :expressionless:

How is that unnecessary overhead? I get handed templates from designers and I put a lot of reuse on my partials to keep my code DRY, front-end and back-end. Especially like this project, when I have 204 date fields with custom JS that I would much rather extract to a partial template.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.