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

后端 未结 2 975
余生分开走
余生分开走 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 = "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;
        });
    

提交回复
热议问题