Laravel blade @include view using variable
Asked Answered
T

2

7

I have a few blade template files which I want to include in my view dynamically based on the permissions of current user stored in session. Below is the code I've written:

@foreach (Config::get('constants.tiles') as $tile)
    @if (Session::get('currentUser')->get('permissions')[$tile]['read'] == 1)
        @include('dashboard.tiles.' . $tile)
    @endif
@endforeach

Blade is not allowing me to concatenate the constant string with the value of variable $tile. But I want to achieve this functionality. Any help on this would be highly appreciated.

Toplevel answered 15/1, 2015 at 12:5 Comment(3)
echo $tile & ensure that it is there. It should work fine if other things are ok.Horton
Try [{$tile}] - does that fix it?Wrac
NOTE: @include('dashboard.tiles.' . $tile) works in Laravel 5.4Thimerosal
A
19

You can not concatenate string inside blade template command. So you can do assigning the included file name into a php variable and then pass it to blade template command.

@foreach (Config::get('constants.tiles') as $tile)
   @if (Session::get('currentUser')->get('permissions')[$tile]['read'] == 1)
     <?php $file_name = 'dashboard.tiles.' . $tile; ?>
     @include($file_name)
   @endif
@endforeach

Laravel 5.4 - the dynamic includes with string concatenation works in blade templates

@foreach (Config::get('constants.tiles') as $tile)
   @if (Session::get('currentUser')->get('permissions')[$tile]['read'] == 1)
     @include('dashboard.tiles.' . $tile)
   @endif
@endforeach
Anglesey answered 11/2, 2015 at 2:50 Comment(1)
Yeah, I did the same but in Controller and then sent the view names as array in view.Toplevel
C
-1

You can use PHP code normally inside the @include. For example, if you want to concatenate a string and a variable simply do this:

@include('string'.$var)

If you can not, maybe you need to download the proper extension in your code editor. In VS Code, Laravel Blade Snippets.

Cargile answered 1/9 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.