1

I'm practicing with Symfony 4 and I am trying to show my images through CSS. Now when I run npm run dev it only compiles the CSS and JS files but not the images. I moved al the images to the /assets/img/ folder.

Now I'm eager to know how I can work with the CSS paths to adapt to the Symfony environment. I only found solutions regarding Symfony 2 and 3 which are not working in this version. My CSS is:

.about-solution-about {
  background: url(/img/placeholder.jpg) no-repeat center;
  background-size: cover;
  width: 540px;
  height: 330px;
  padding-top: 40px;
}

The image is now in this location: project/assets/img/placeholder.jpg

Somehow I need to access this image in the public folder through the compiled app.css file. I know that the app.css and the app.js files are compiled and placed in the /public/build/ folder.

Now, how do I compile or build all the image assets to the /public/build/ folder and recall those files in my CSS?

3 Answers 3

1

The building of the regular CSS and JS assets in the /assets/ folder are handled by the Webpack Encore webpack.config.js file in your project directory.

When you run the npm run dev command in your terminal the files app.css and app.js are compiled and placed in the /public/build/ folder.

If you also want images included in the /public/build/ folder you can make use of the Copy Webpack Plugin.

First, install the plugin with the npm i -D copy-webpack-plugin command in your terminal.

Then edit the webpack.config.js file in your home project folder. Under the first line, add:

var CopyWebpackPlugin = require('copy-webpack-plugin');

And then right before the Encore section ends with a semicolon ;, add:

.addPlugin(new CopyWebpackPlugin([
        { from: './assets/img', to: 'img' }
    ]))

JSFiddle example of the whole file here.

Now, make sure that you have images in the /assets/img/ folder.

Run the npm run dev command and you 'll see that all your images from the assets folder are now available in the /public/build/img/ folder!!

In your example the correct path in your CSS would now be:

background: url(/build/img/placeholder.jpg) no-repeat center;
Sign up to request clarification or add additional context in comments.

Comments

0

You could try to use cssrewrite filter within stylesheets twig tag / base twig /:

{% stylesheets 'source to css files' filter='cssrewrite' %}

{% endstylesheets %}

Comments

0

I think there's no way to work with Assets in pure CSS code. I recommend you to set the background parameter in your HTML, where you actually can. Hope you figure it out!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.