Tom P
Tom P

Reputation: 133

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?

Upvotes: 12

Views: 10351

Answers (2)

Claire Mcevoy
Claire Mcevoy

Reputation: 43

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;
    });

Upvotes: 1

BARNZ
BARNZ

Reputation: 1329

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')

Upvotes: 25

Related Questions