Including Assets (CSS, JS) in Symfony 4 / Twig Template

yevg picture yevg · Feb 21, 2018 · Viewed 22k times · Source

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

  • Restarting my local Symfony server
  • moving the asset to an assets folder at the root at adjusting the link accordingly
  • verifying that the asset package was installed (it is)
  • googling this issue (nothing for Symfony 4)

Questions

  • 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?

Answer

simshaun picture simshaun · Feb 21, 2018

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.