How to have background image in symfony assets?

2019-08-07 03:33发布

问题:

with symphony framework I did dump assets assets:install. css file is hard copied to /web/bundles/appbundle/css/style.css I guess for background image in css I should have a relative path to reach outside of /web/ folder like this?

background-image: url(../../../../bundles/appbundle/images/top_bg.jpg);

but it doesn't work yet, I have filter='cssrewrite' in css tag too. probably I have to add that I am only editing the css file located at the path above after assets install, I did not edit the one in /Acme/Bundle/Resources/public/css any more. Then I did run assets:dump, now in /web/ folder there are two folders for images and css, I looked at new css and see the path became like this:

background-image: url(../../bundles/applicationadmin/images/top_bg.jpg);

But still all images are broken. I search stackoverflow and found this question, but still have problem. what else should I do?

please advice.

回答1:

First of all, make sure that your css and images are inside correct folder.

src/AppBundle/Resources/public/css/style.css
src/AppBundle/Resources/public/images/top_bg.jpg

After you run assets assets:install, check if there is a folder on your web directory. It have to be a identical copy from Resources/public.

web/bundles/app/css/style.css
web/bundles/app/images/top_bg.jpg

And your style.css file should look like this:

background-image: url("../../images/top_bg.jpg");

However, if you are configuring the css directly on twig template, the url is different:

<style>
  div { background-image: url("/bundles/app/images/top_bg.jpg"); }
</style>


回答2:

To make it work in twig try this

<div class="container" style="background-image:url('{{ asset('bundles/appbundle/images/top_bg.jpg') }}')"> , 

of course presuming that you have installed the bundle's web assets under a public web directory.