Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel blade include files with relative path

Tags:

laravel

blade

In laravel blade system when we want to include a partial blade file we have to write the full path every time for each file. and when we rename a folder then we will have to check every @include of files inside it. sometimes it would be really easy to include with relative paths. is there any way to do that?

for example we have a blade file in this path :

resources/views/desktop/modules/home/home.blade.php

and I need to include a blade file that is near that file :

@include('desktop.modules.home.slide')

with relative path it would be something like this :

@include('.slide')

is there any way to do this?

like image 724
Amin Adel Avatar asked Apr 18 '18 07:04

Amin Adel


2 Answers

if someone still interest with relative path to current view file, put this code in the boot method of AppServiceProvider.php or any provider you wish

    Blade::directive('relativeInclude', function ($args) {
        $args = Blade::stripParentheses($args);

        $viewBasePath = Blade::getPath();
        foreach ($this->app['config']['view.paths'] as $path) {
            if (substr($viewBasePath,0,strlen($path)) === $path) {
                $viewBasePath = substr($viewBasePath,strlen($path));
                break;
            }
        }

        $viewBasePath = dirname(trim($viewBasePath,'\/'));
        $args = substr_replace($args, $viewBasePath.'.', 1, 0);
        return "<?php echo \$__env->make({$args}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>";
    });

and then use

    @relativeInclude('partials.content', $data) 

to include the content.blade.php from the sibling directory called partials

good luck for everyone

like image 118
Medo Avatar answered Sep 16 '22 15:09

Medo


you need to create custom blade directive for that, the native include directive doesn't work like that.

read this page to learn how to create custom blade directive :

https://scotch.io/tutorials/all-about-writing-custom-blade-directives

\Blade::directive('include2', function ($path_relative) {
    $view_file_root = ''; // you need to find this path with help of php functions, try some of them.
    $full_path = $view_file_root . path_relative;
    return view::make($full_path)->render();
});

then in blade file you can use relative path to include view files :

@include2('.slide')

I tried to tell you the idea. try and test yourself.

like image 24
Emin Gorgani Avatar answered Sep 18 '22 15:09

Emin Gorgani