Im learning Symfony and trying to set up a boilerplate app in Symfony 4
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" />
I have installed this package and trying to link to a css file in my /public
directory.
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.
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>
Problem
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
.
Its as if the asset()
function is not even used.
Ive tried
assets
folder at the root at adjusting the link accordinglyasset
package was installed (it is)Questions
public/*
path is a filesystem path to assets, NOT a URL route, and include my assets successfully? /assets
folder at the root?Templates in Symfony are created with Twig: a flexible, fast, and secure template engine.
A web asset can be: Cascading Style Sheet (CSS) files. JavaScript files. Snippets — A short fragment of HTML code for inserting in the DOM at required locations. Widget — A special mini function to generate HTML in predefined locations on a page.
Paths in the asset
function should be relative to your public directory, not the project root.
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.
Firstly maybe you have to add the asset functionality to Symfony:
composer require symfony/asset
Then you should to use in Twig temlate the relative path to your public directory:
<link href="{{ asset('css/style.css') }}" rel="stylesheet" />
for the public/css/style.css
style file.
BTW it is also works for Symfony 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With