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

问题描述 投票:0回答:4

在 Laravel Blade 系统中,当我们想要包含部分 Blade 文件时,我们必须每次都为每个文件写入完整路径。当我们重命名一个文件夹时,我们必须检查其中每个文件的@include。有时包含相对路径确实很容易。有什么办法可以做到吗?

例如我们在这个路径中有一个blade文件:

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

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

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

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

@include('.slide')

有什么办法可以做到这一点吗?

laravel laravel-blade
4个回答
7
投票

如果有人仍然对当前视图文件的相对路径感兴趣,请将此代码放入 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(); ?>";
    });

然后使用

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

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

祝大家好运


4
投票

有一个(现已不再维护)包可以使用 lfukumori/laravel-blade-include-relative

@include
@includeIf
@includeWhen
@each
指令进行相对和绝对包含 (
@includeFirst
)。我刚刚把它拉到一个项目中,效果很好。


3
投票

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

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

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

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

@include2('.slide')

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

© www.soinside.com 2019 - 2024. All rights reserved.