|
| 1 | +Copying & Referencing Images |
| 2 | +============================ |
| 3 | + |
| 4 | +Need to reference a static file - like the path to an image for an ``img`` tag? |
| 5 | +That can be tricky if you store your assets outside of the public document root. |
| 6 | +Fortunately, depending on your situation, there is a solution! |
| 7 | + |
| 8 | +Referencing Images from Inside a Webpacked JavaScript File |
| 9 | +---------------------------------------------------------- |
| 10 | + |
| 11 | +To reference an image tag from inside a JavaScript file, *require* the file: |
| 12 | + |
| 13 | +.. code-block:: javascript |
| 14 | +
|
| 15 | + // assets/js/app.js |
| 16 | +
|
| 17 | + // returns the final, public path to this file |
| 18 | + // path is relative to this file - e.g. assets/images/logo.png |
| 19 | + const logoPath = require('../images/logo.png'); |
| 20 | +
|
| 21 | + var html = `<img src="${logoPath}">`; |
| 22 | +
|
| 23 | +When you ``require`` (or ``import``) an image file, Webpack copies it into your |
| 24 | +output directory and returns the final, *public* path to that file. |
| 25 | + |
| 26 | +Referencing Image files from a Template |
| 27 | +--------------------------------------- |
| 28 | + |
| 29 | +To reference an image file from outside of a JavaScript file that's processed by |
| 30 | +Webpack - like a template - you can use the ``copyFiles()`` method to copy those |
| 31 | +files into your final output directory. |
| 32 | + |
| 33 | +.. code-block:: diff |
| 34 | +
|
| 35 | + // webpack.config.js |
| 36 | +
|
| 37 | + Encore |
| 38 | + // ... |
| 39 | + .setOutputPath('web/build/') |
| 40 | +
|
| 41 | + + .copyFiles({ |
| 42 | + + from: './assets/images', |
| 43 | + + |
| 44 | + + // optional target path, relative to the output dir |
| 45 | + + //to: 'images/[path][name].[ext]', |
| 46 | + + |
| 47 | + + // only copy files matching this pattern |
| 48 | + + //pattern: /\.(png|jpg|jpeg)$/ |
| 49 | + + }) |
| 50 | +
|
| 51 | +This will copy all files from ``assets/images`` into ``web/build`` (the output |
| 52 | +path). If you have :doc:`versioning enabled <versioning>`, the copied files will |
| 53 | +include a hash based on their content. |
| 54 | + |
| 55 | +To render inside Twig, use the ``asset()`` function: |
| 56 | + |
| 57 | + {# assets/images/logo.png was copied to web/build/logo.png #} |
| 58 | + <img src="{{ asset('build/logo.png') }}" |
| 59 | + |
| 60 | + {# assets/images/subdir/logo.png was copied to web/build/subdir/logo.png #} |
| 61 | + <img src="{{ asset('build/subdir/logo.png') }}" |
| 62 | + |
| 63 | +Make sure you've enabled the :ref:`json_manifest_path <load-manifest-files>` option, |
| 64 | +which tells the ``asset()`` function to read the final paths from the ``manifest.json`` |
| 65 | +file. If you're not sure what path argument to pass to the ``asset()`` function, |
| 66 | +find the file in ``manifest.json`` and use the *key* as the argument. |
0 commit comments