在 Symfony 5 的模板子文件夹中使用 public 文件夹中的文件

Use files in the public folder within template subfolder in Symfony 5

我目前在我的 Twig 模板中使用 CSS。 CSS 在我的 public 文件夹中,模板在模板文件夹中。 所以下面的代码实际上是有效的:<link rel="stylesheet" href="assets/libs/css/style.css">

问题来了。我在模板文件夹中创建了一个子目录,但是当我像以前一样尝试访问 CSS 时; Symfony 找不到我的 CSS 文件。 我通过在 href 之前使用 ../ 解决了这个问题,所以我有这个:<link rel="stylesheet" href="../assets/libs/css/style.css">

此时我的问题已解决,但我想要比 ../ 更通用的东西,因为如果我在模板文件夹内的文件夹中有一些文件夹,我会有类似的东西 ../../../而且真的很丑

所以我目前正在寻找一种通用方法来访问 public 文件夹,无论我在模板文件夹中的什么位置。 如果我的问题不够清楚,我知道如何在 Blade 中用 {{ URL::to('/') }} 做到这一点,所以在 Blade 中我的代码会是这样的:<link rel="stylesheet" href="{{ URL::to('/') }}/assets/libs/css/style.css">

Symfony 有一个 twig 函数,可以作为 Asset-component 的一部分。如果你使用 Webpack Encore,你可能已经安装了它,否则你可以通过 composer 安装它:

composer require asset

这应该会为您创建一个默认配置,您应该能够在您的模板中使用以下内容:

{{ asset('/assets/libs/css/style.css') }}

作为 Linking to CSS, JavaScript and Image Assets 状态的文档:

The asset() function's main purpose is to make your application more portable. If your application lives at the root of your host (e.g. https://example.com), then the rendered path should be /images/logo.png. But if your application lives in a subdirectory (e.g. https://example.com/my_app), each asset path should render with the subdirectory (e.g. /my_app/images/logo.png). The asset() function takes care of this by determining how your application is being used and generating the correct paths accordingly.