Symfony 4 webpack + encore handle image in template

Vincent Decaux picture Vincent Decaux · Dec 31, 2017 · Viewed 9.3k times · Source

Using Symfony 4 with Webpack + Encore + Yarn, I want to handle images in my templates, and I am not really how to achieve this.

I put my image in my /assets/img/logo.png folder, and use this in my webpack.config.js:

.addEntry('logo', './assets/img/logo.png')

And after I run :

yarn run encore dev

Which generates /public/build/logo.js and /public/build/images/logo.aez323a.png files.

My question, is there a way to link Symfony asset() function to the file name with the hash in the filename ? or should I use other way to use the image in my templates ?

Answer

knetsi picture knetsi · Dec 31, 2017

It seems that you have enabled the versioning .enableVersioning() , each time you run yarn run encore dev a manifest.json file should be created in your output path, based on your question this path is /public/build. So you will have to add in your settings the following configuration

config/packages/framework.yaml

framework:
    assets:
        json_manifest_path: '%kernel.project_dir%/public/build/manifest.json'

Then you will be able to use the asset() function referencing by name e.g asset('public/images/logo.png')

You can find this information in symfony documentation here