SteeveDroz
SteeveDroz

Reputation: 6136

Symfony 3 set background image using CSS

The answer provided by "Symfony 2 set background image using CSS" doesn't work in Symfony 3 any more. So I ask the very same question for the next version:

I want to put a background image from CSS, how can I do that?

What I tried:

/* src/SiteBundle/Resources/public/css/style.css */
#element {
  background: url('../images/image.jpg');
}

With an image located at src/SiteBundle/Resources/public/images/image.jpg.

Assets are correctly installed with console asset:install --symlink, all green to go.

Assetic is manually installed with composer.

CSS is loaded with:

<!-- app/Resources/views/base.html.twig -->
{% stylesheets '@SiteBundle/Resources/public/css/*.css' filter='cssrewrite' %}
  <link rel="stylesheet" href="{{ asset_url }}" type="text/css">
{% endstylesheets %}

What I got:

When I look at my browser inspector, it tells me that the css property is

background: url('../../Resources/public/images/image.jpg')

which is obviously not working.

What I tried to fix it:

I tried changing the CSS background property to url('images/image.jpg'), knowing it wouldn't work but to figure out how it handles the links.

The browser inspector told me the link was now url('../../Resources/public/css/images/image.jpg'), telling me there is no way I can change the ../../Resources/public/ part.

How am I supposed to to it correctly?

Bonus question you should ask yourself before answering: will your answer work when I switch from dev to prod?

Upvotes: 0

Views: 1999

Answers (1)

malcolm
malcolm

Reputation: 5542

When using the cssrewrite filter, don't refer to your CSS files using the @AppBundle syntax. http://symfony.com/doc/current/cookbook/assetic/asset_management.html#fixing-css-paths-with-the-cssrewrite-filter

also:

Best Practice:

Store your assets in the web/ directory.

So you probably should use:

{% stylesheets 'bundles/site/css/*.css' filter='cssrewrite' %}
    <link rel="stylesheet" href="{{ asset_url }}" type="text/css">
{% endstylesheets %}

Is this work for both prod and dev? I really don't know since i'm using gulp to manage assets.

Upvotes: 1

Related Questions