Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blade templates recursive includes

I have an array of items that represent the file and dir structure of a directory on the server.

The $items array is constructed like this:

Array
(
    [folder1] => Array
        (
            [folder1_1] => Array
                (
                    [0] => filenameX.txt
                    [1] => filenameY.txt
                )
        )
    [pages] => Array
        (
        )
    [0] => filename.txt
    [1] => filename1.txt
)

what we want, is essentially <ul> with <li> for every node.

the resulting HTML should be something like

  • folder1/
    • folder1_1/
      • filenameX.txt
      • filenameY.txt
  • pages/
  • filename_1.txt
  • filename_2.txt

Now, my question has to do with nested includes with laravel's blade templating engine.

I have a view list.blade.php with the following contents

<div class="listing">
  @include('submenu', array('items', $items))
</div>

and I pass it the array like this:

View::make('list')->with('items', $items)

the included template (submenu.blade.php) has the following:

<ul>
@foreach($items as $key=>$value)
    @if (is_array($value))
        <li>{{$key}}/
        @include('submenu', array('items', $value))
        </li>
    @else
        <li>{{$value}}</li>
    @endif
@endforeach
</ul>

I @include the same template from within itself but with the new data, in case the $value is an array (directory)

First of all, is this at all possible?

If not, is there another way to achive the desired result?

TIA,

like image 487
papas-source Avatar asked Mar 12 '14 18:03

papas-source


1 Answers

Yes, this is indeed possible.

However, there's an issue in your includes, you have:

@include('submenu', array('items', $value))

It should be:

@include('submenu', array('items' => $value))

It's worth noting also another hidden blade statment, @each. You can use this instead of looping through the array yourself, something like this:

<ul>
    @each('item.detail', $items, 'item')
</ul>

Then you create a new blade file named item.detail and pop what you previously had in your loop in that file. It helps to clean up your view from having more and more nested loops.

The data for the item when you are inside your new blade file will be held in the third parameter, in this case $item

like image 51
duellsy Avatar answered Sep 21 '22 15:09

duellsy