Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a view exists and do an @include in Laravel Blade

With Laravel Blade, is there an elegant way to check if a view exists before doing an @include?

For example I'm currently doing this:

@if(View::exists('some-view'))
    @include('some-view')
@endif

Which gets quite cumbersome when 'some-view' is a long string with variables inside.

Ideally I'm looking for something like this:

@includeifexists('some-view')

Or to make @include just output an empty string if the view doesn't exist.

As an aside, I would also like to provide a set of views and the first one that exists is used, e.g.:

@includefirstthatexists(['first-view', 'second-view', 'third-view'])

And if none exist an empty string is output.

How would I go about doing this? Would I need to extend BladeCompiler or is there another way?

like image 432
Tom P Avatar asked Feb 04 '16 10:02

Tom P


2 Answers

Had a similar issue. Turns out that from Laravel 5.3 there is an @includeIf blade directive for this purpose.

Simply do @includeIf('some-view')

like image 148
BARNZ Avatar answered Nov 14 '22 09:11

BARNZ


I created this blade directive for including the first view that exists, and returns nothing if none of the views exist:

Blade::directive('includeFirstIfExists', function ($expression) {

        // Strip parentheses
        if (Str::startsWith($expression, '(')) {
            $expression = substr($expression, 1, -1);
        }

        // Generate the string of code to render in the blade
        $code = "<?php ";
        $code .= "foreach ( {$expression} as \$view ) { ";
        $code .=  "if ( view()->exists(\$view) ) { ";
        $code .= "echo view()->make(\$view, \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ";
        $code .= "break; } } ";
        $code .= "echo ''; ";
        $code .= "?>";

        return $code;
    });
like image 1
Claire Mcevoy Avatar answered Nov 14 '22 10:11

Claire Mcevoy