Search code examples
phpcssimagesymfonyassetic

Symfony assetic cssrewrite image path in app/Resources


I've got a problem with assetic and the path of my images in CSS on Symfony. My base template, my base CSS, and the images used in this CSS are in the folder app/Resources.

I have this:

app/
    Resources/
        public/
            css/
                base.css
            images/
                mybackground.png
    views/
        base.html.twig

In the file base.css, I want to load the file mybackground.css as a background, so I have this line:

background-image: url('../images/mybackground.png');

And in the file 'base.html.twig', I load the css with:

{% stylesheets '@base_css' filter='cssrewrite' %}

<link rel="stylesheet" type="text/css" charset="utf-8" media="all" href="{{ asset_url }}" />

{% endstylesheets %}

I also tried without the filter cssrewrite.

In app/config/config.yml, I have this:

assetic:
filters:
    cssrewrite: ~
assets:
    base_css:
        inputs:
            - '../app/Resources/public/css/base.css'

Before try, I used all of these commands:

php app/console cache:clear
php app/console cache:clear --env=prod
php app/console assetic:dump
php app/console assetic:dump --env=prod --no-debug
php app/console assets:install --symlink web

As you can guess, my background image isn't loaded (the browser returns a 404 not found error). I searched a lot on internet, and I found similar cases but with the resources in some bundles not in app/Resources.


Solution

  • When you create a public directory in the Resources directory of your bundle, and run the assets:install --symlink command, a symbolic link is created in the web/bundles directory, corresponding to the name of your bundle.

    Also, to retrieve your image, you should use the relative path of the web directory instead of the absolute path of your asset, which is :

    /bundles/bundlename/images/background.jpg
    

    EDIT

    If you really doesn't want to place them inside a bundle, just move them from the app/Resources directly to the web folder, and call it in your css using :

    url('/images/background.jpg');
    

    See symfony2 how to access app/Resources/img from browser?