Laravel Blade 包含具有相对路径的文件

Ami*_*del 7 laravel blade

在 laravel 刀片系统中,当我们想要包含部分刀片文件时,我们必须每次为每个文件编写完整路径。当我们重命名一个文件夹时,我们将不得不检查其中的每个@include 文件。有时包含相对路径真的很容易。有没有办法做到这一点?

例如,我们在此路径中有一个刀片文件:

resources/views/desktop/modules/home/home.blade.php
Run Code Online (Sandbox Code Playgroud)

我需要包含一个靠近该文件的刀片文件:

@include('desktop.modules.home.slide')
Run Code Online (Sandbox Code Playgroud)

使用相对路径,它将是这样的:

@include('.slide')
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Moh*_*Ani 8

如果有人仍然对当前视图文件的相对路径感兴趣,请将此代码放入 AppServiceProvider.php 或您希望的任何提供程序的 boot 方法中

    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(); ?>";
    });
Run Code Online (Sandbox Code Playgroud)

然后使用

    @relativeInclude('partials.content', $data) 
Run Code Online (Sandbox Code Playgroud)

包含名为partials的同级目录中的content.blade.php

祝大家好运


Emi*_*ani 2

您需要为此创建自定义刀片指令,本机include指令不能那样工作。

阅读此页面以了解如何创建自定义刀片指令:

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();
});
Run Code Online (Sandbox Code Playgroud)

然后在 Blade 文件中,您可以使用相对路径来包含视图文件:

@include2('.slide')
Run Code Online (Sandbox Code Playgroud)

我试图告诉你这个想法。尝试测试一下自己。