Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel blade custom directive with include partial

I have a custom Blade directive from which I'm trying to include a partial with the Blade syntax @include(). The problem is that I have a custom views namespace:

\Blade::directive('name', function() {
    $viewsNamespace = 'viewsNameSpace::';
    $formPartial = $viewsNamespace . 'partials._form';
    return "{{ @include({$formPartial}) }}";
});

This outputs the error,

Class 'viewsNameSpace' not found

because its interpreting viewsNameSpace:: as a class.

This outputs just the string without parsing it:

return "@include('{$formPartial}')";

And this is not throwing any errors but its not loading the partial:

return "{{ @include('{$formPartial}') }}";

Please note that the partial is working when I'm using in in a template like this:

@include('viewsNameSpace::partials._form')

but I can't make it work from the directive.

Any help and suggestions would be appreciated! Thank you!

like image 950
thefallen Avatar asked Aug 09 '16 08:08

thefallen


2 Answers

This is how I made it work:

return "<?php echo view('$formPartial')->render(); ?>";

Where $formPartial is 'viewsNameSpace::partials._form'.

like image 82
thefallen Avatar answered Nov 13 '22 05:11

thefallen


If anyone comes across this question since its post in '16, Laravel now has a blade helper to create a custom include directive (since version 5.6.5):

Blade::include('viewsNameSpace::path.to.view.file');

This is to be added to the boot() method of your app service provider. More examples here.

like image 26
thisiskelvin Avatar answered Nov 13 '22 04:11

thisiskelvin