laravel blade包含具有相对路径的文件

时间:2018-04-18 07:58:10

标签: laravel blade

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

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

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

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

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

相对路径会是这样的:

@include('.slide')

有没有办法做到这一点?

6 个答案:

答案 0 :(得分:2)

您需要为此创建自定义的Blade指令,原生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();
});

然后在刀片文件中,您可以使用相对路径包括视图文件:

@include2('.slide')

我试图告诉你这个主意。尝试测试一下自己。

答案 1 :(得分:2)

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

    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(); ?>";
    });

然后使用

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

包含来自名为partials的兄弟目录中的content.blade.php

祝大家好运

答案 2 :(得分:2)

一个时尚的选项,如果您想在子文件夹中组织视图文件:

public function ...(Request $request) {
    $blade_path = "folder.subfolder.subsubfolder.";
    $data = (object)array(
        ".." => "..",
        ".." => $..,
        "blade_path" => $blade_path,
    );
    return view($data->blade_path . 'view_file_name', compact('data'));
}

然后在视图刀片中(或您要包括的其他位置):

@include($blade_path . 'another_view_file_name')

答案 3 :(得分:1)

现在有一个同时使用相对和绝对包含(lfukumori/laravel-blade-include-relative)的程序包,它们与@include@includeIf@includeWhen@each和{{1} }指令。我只是将其拉到一个项目中,效果很好。

答案 4 :(得分:0)

据我所知,这还没有在Laravel中实现。

我在快速搜索后找到了

Here is a workaround

答案 5 :(得分:0)

  

您可以在controller

中执行此操作
use \resources\views\desktop\modules\home;

并在views

中使用
@include('home');
相关问题