Symfony 4 webpack + encore handle image in template

橙三吉。 提交于 2019-12-10 11:25:59

问题


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 ?


回答1:


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




回答2:


There is copyFiles now - official encore plugin: https://symfony.com/doc/current/frontend/encore/copy-files.html

In short, you put images in /assets/images (or any other), at build time plugin copy this folder to /public/build with same subfolder structure. All you need to do is add some strings to /webpack.config.js - plugin activation with "from" and "to" variables.

In twig use those images as usual with {{ asset(path_in_public) }}.

if you enable dev server for hot reload

$ yarn encore dev-server

than files from /assets/images will be available in twig templates even without physical copy in /public.

Files will be physically copied when you execute

$ yarn encore prod


来源:https://stackoverflow.com/questions/48042006/symfony-4-webpack-encore-handle-image-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!