How to include css in symfony 5?

Member

by addison , in category: PHP Frameworks , 9 months ago

How to include css in symfony 5?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 9 months ago

@addison 

To include CSS in Symfony 5, you can follow these steps:

  1. Create a CSS file in the public/css directory of your Symfony project.
  2. Open the webpack.config.js file located in the root directory of your Symfony project.
  3. Inside the Encore configuration block, add the following code to include the CSS file:
1
2
3
4
5
6
7
Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addStyleEntry('css/main', './public/css/main.css')
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())


In this example, main.css is the name of your CSS file. You can change it to match the name of your CSS file.

  1. Save the webpack.config.js file.
  2. Open your Symfony template file (e.g., templates/base.html.twig). Include the CSS file by adding the following code inside the section:
1
2
3
{% block stylesheets %}
    {{ encore_entry_link_tags('css/main') }}
{% endblock %}


Make sure to replace main with the name you specified in the webpack.config.js file.

  1. Finally, run the Encore command to compile and include the CSS file:
1
$ yarn encore dev


If you don't have Yarn installed, you can use the following command instead:

1
$ npm run encore dev


That's it! Your CSS file should now be included in your Symfony application. You can also use this method to include multiple CSS files by repeating steps 1-5 for each file.