Reputation: 3999
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?
Upvotes: 1
Views: 5803
Reputation: 3999
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;
Upvotes: 1
Reputation: 347
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!
Upvotes: 0
Reputation: 743
You could try to use cssrewrite filter within stylesheets twig tag / base twig /:
{% stylesheets 'source to css files' filter='cssrewrite' %}
{% endstylesheets %}
Upvotes: 0