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

后端 未结 2 976
余生分开走
余生分开走 2021-02-08 02:48

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(V         


        
相关标签:
2条回答
  • 2021-02-08 03:22

    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;
        });
    
    0 讨论(0)
  • 2021-02-08 03:44

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

    0 讨论(0)
提交回复
热议问题