在Symfony 4/Twig模板中包含资产(CSS,JS) [英] Including Assets (CSS, JS) in Symfony 4 / Twig Template
问题描述
我正在学习Symfony,并尝试在Symfony 4中设置样板应用程序
Im learning Symfony and trying to set up a boilerplate app in Symfony 4
此Symfony文档描述了如何在页面中包含资产,即使用<像这样的code> asset 包..
This Symfony document describes how to include assets in your page, namely using the asset
package like so..
<img src="{{ asset('images/logo.png') }}" alt="Symfony!" />
<link href="{{ asset('css/blog.css') }}" rel="stylesheet" />
我已经安装了此软件包,并尝试链接到我的/public
目录中的css文件.
I have installed this package and trying to link to a css file in my /public
directory.
我知道Symfony建议将资产放在根目录下的/assets
文件夹中,但我想避免这种情况.对我来说,将资产放在公共目录中更有意义.
I know Symfony recommends placing assets in an /assets
folder at the root, but I would like to avoid this if possible. It makes more sense to me to place assets in the public directory.
我的Twig基本模板如下:
My Twig base template is as follows:
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}
<link href="{{ asset('public/css/main.css') }}" rel="stylesheet" />
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
<footer>footer</footer>
</html>
问题
当我加载路线/页面/模板时,链接的css呈现为来自根的简单链接(好像Im将其链接为< link href ="public/css/main.css" rel="stylesheet"/>
-当然,没有为 public/*
设置任何路由,这将返回 404/Not Found
.
When I load the route/page/template, the linked css is rendered as a simple link from the root (as if Im linking it as <link href="public/css/main.css" rel="stylesheet" />
- there is of course no route set for public/*
and this returns 404/Not Found
.
就好像没有使用 asset()
函数一样.
Its as if the asset()
function is not even used.
我已经尝试过
- 重新启动本地Symfony服务器
- 在相应调整链接时将资产移动到根目录下的
assets
文件夹中 - 验证是否已安装
asset
软件包 - 搜索此问题(Symfony 4无关)
问题
- 如何让Symfony知道
public/*
路径是资产的文件系统路径,而不是URL路径,并且成功包含了我的资产? - 除了推荐的
/assets
文件夹的根目录以外,是否有其他功能可以为资产设置默认位置?
- How can I let Symfony know that the
public/*
path is a filesystem path to assets, NOT a URL route, and include my assets successfully? - Is there such a feature to set a default location for assets other than the recommended
/assets
folder at the root?
推荐答案
asset
函数中的路径应相对于您的公共目录,而不是项目根目录.
Paths in the asset
function should be relative to your public directory, not the project root.
因此,假设您服务器的docroot是 public_html
,而资产位于 public_html/css/main.css
中,则资产调用将是 {{asset('css/main.css')}}
.
So, pretending your server's docroot is public_html
, and an asset is in public_html/css/main.css
, the asset call would be {{ asset('css/main.css') }}
.
附加说明:资产功能无法让您将资产置于公共目录之外.它们必须在公共目录中.
Additional note: The asset function doesn't give you the ability to put assets outside the public directory. They must be in the public directory.
这篇关于在Symfony 4/Twig模板中包含资产(CSS,JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!