Laravel blade 查看相对路径

Laravel blade view relative path

我的 Laravel Blade 观点需要帮助。目前我每次都使用 <link href="{{asset('css/sample.css')}}" rel="stylesheet"> 在我的 public 文件夹中生成我的 sample.css 的路径。它会生成类似 <link href="http://mydomainname/css/sample.css" rel="stylesheet"> 的东西,并且运行良好 (我的 public 文件夹在我的 public_html 文件夹 cpanel 托管上).

但是,我想使用相对路径而不是直接 link 到我的 css 文件。我想使用一种更简单的方法,如 <link href="css/sample.css" rel="stylesheet">,如果我在根路径上工作,它会起作用,但当它进入我网站的更深层路径时,它就不起作用了。

谁能帮助我生成 css 文件的相对路径?

谢谢。

这可以使用您建议的更简单的方法来实现,您只是缺少一个 /

如果您 link 使用这样的路径访问您的 CSS 文件; /css/sample.css 然后它告诉浏览器获取与根 URL 相关的文档。这对于您使用的任何资产都是一样的。

所以作为 HTML link 它将是:

<link href="/css/sample.css" rel="stylesheet">

这会告诉浏览器,无论您在哪个页面上,都从 http(s)://example.com/css/sample.css 获取 sample.css 文件。

如果没有开头的 /,您的 link 表示相对于当前页面获取它; http(s)://example.com/your/page/url/css/sample.css。在您的主页上,这显然会成功,因为 URL 仍会解析为 http(s)://example.com/css/sample.css

根据 this,您只需编辑位于 public 文件夹中的 index.php,如下所示:

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

// set the public path to this directory
$app->bind('path.public', function() {
    return __DIR__;
});

通过将vendor\laravel\framework\src\Illuminate\Foundation\helpers.php修改为:

解决了
function asset($path, $secure = null)
{
    $url = app('url')->asset($path, $secure);
    return parse_url($url, PHP_URL_PATH);
}

我的 laravel 中的所有 asset() 代码现在只生成路径(通过删除域 URL)并在我的产品或本地主机上工作