Copying Files

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Do a force refresh on the homepage. Ok, we've got some broken images. Inspect that. Of course: this points to /images/meteor-shower.jpg.

Open this template: article/homepage.html.twig. There it is:

... lines 1 - 2
{% block body %}
<div class="container">
<div class="row">
<!-- Article List -->
<div class="col-sm-12 col-md-8">
<!-- H1 Article -->
<a class="main-article-link" href="#">
<div class="main-article mb-5 pb-3">
<img src="{{ asset('images/meteor-shower.jpg') }}" alt="meteor shower">
... line 15
</div>
</a>
... lines 18 - 40
</div>
... lines 42 - 61
</div>
</div>
{% endblock %}

A normal asset() function pointing to images/meteor-shower.jpg. That's broken because we moved our entire images/ directory out of public/ and into assets/.

There's a nice side-effect of using a build system like Webpack: you don't need to keep your CSS, JavaScript or assets in a public directory anymore! You put them in assets/, organize them however you want, and the end-user will only ever see the final, built version.

But unless you're building a single page application, you'll probably still have some cases where you want to render a good, old-fashioned img tag. And because this image is not being processed through Webpack, it's not being copied into the final build/ directory.

Hello copyFiles()

To make life more joyful, Encore has a feature for exactly this situation. Open up webpack.config.js. And, anywhere in here, say .copyFiles() and pass this a configuration object:

... lines 1 - 2
Encore
... lines 4 - 53
.copyFiles({
... line 55
})
... lines 57 - 70
;
... lines 72 - 73

Obviously... this function helps you copy files from one place to another. Neato! But... how exactly do we use it? One of the nicest things about Encore is that its code is extremely well-documented. Hold Command or Ctrl and click copyFiles(). It jumps us straight to the index.js file of Encore... which is almost entirely small methods with HUGE docs above them! This is a great resource for finding out, not only how you can use a function, but what functions and features are even available!

For copyFiles(), it can be as simple as:

I want to copy everything from assets/images into my build directory.

Yea, that sounds about right. If we did that, we could then reference those images from our img tags. Copy that config, go back to webpack.config.js and paste. Oh, I have an extra set of curly braces:

... lines 1 - 2
Encore
... lines 4 - 53
.copyFiles({
from: './assets/images'
})
... lines 57 - 70
;
... lines 72 - 73

And because we just made a change to webpack.config.js, find your terminal, press Ctrl+C, and re-run Encore. When that finishes... go check it out. In the public/build/ directory, there they are: meteor-shower.jpg, space-ice.png and so on.

Controlling the copy Destination

Um, but it is kind of lame that it just dropped them directly into build/, I'd rather, for my own sanity, copy these into build/images/.

Let's see... go back to the docs. Here it is: you can give it a destination... and this has a few wildcards in it, like [path], [name] and [ext]. Oh, but use this second one instead: it gives us built-in file versioning by including a hash of the contents in the filename.

Back in our config, paste that:

... lines 1 - 2
Encore
... lines 4 - 53
.copyFiles({
from: './assets/images',
to: 'images/[path][name].[hash:8].[ext]'
})
... lines 58 - 71
;
... lines 73 - 74

Before we restart Encore, shouldn't we delete some of these old files... at least to get them out of the way and clean things up? Nope! Well, yes, but it's already happening. One other optional feature that we're using is called cleanOutputBeforeBuild():

... lines 1 - 2
Encore
... lines 4 - 38
.cleanupOutputBeforeBuild()
... lines 40 - 71
;
... lines 73 - 74

This is responsible for emptying the build/ directory each time we build.

Ok, go restart Encore: Ctrl+C, then:

yarn watch

Let's go check it out! Beautiful! Everything now copies to images/ and includes a hash.

Public Path to Versioned Copied Files: manifest.json

Oh, but... that's a problem. What path are we supposed to use for the img tag? Should we put build/images/meteor-shower.5c77...jpg? No, because if we ever updated that image, the hash would change and all our img tags would break. And because they aren't being processed by Webpack, that failure would be the worst kind: it would fail silently!

In the build/ directory, there are two special JSON files generated by Encore. The first - entrypoints.json - is awesome because the Twig helpers can use it to generate all of the script and link tags for an entry. But there's another file: manifest.json.

This is a big, simple, beautiful map that contains every file that Encore outputs. It maps from the original filename to the final filename. For most files, because we haven't activated versioning globally yet, the paths are the same. But check out the images! It maps from build/images/meteor-shower.jpg to the real, versioned path! If we could read this file, we could automagically get the correct hash!

When we installed WebpackEncoreBundle, the recipe added a config/packages/assets.yaml file. Inside, oh! It has json_manifest_path set to the path to manifest.json:

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

The significance of this line is that anytime we use the asset() function in Twig, it will take that path and look for it inside of manifest.json. If it finds it, it will use the final, versioned path.

This means that if we want to point to meteor-shower.jpg, all we need to do is use the build/images/meteor-shower.jpg path. Copy that, go to the homepage template, and paste it here:

... lines 1 - 2
{% block body %}
<div class="container">
<div class="row">
<!-- Article List -->
<div class="col-sm-12 col-md-8">
<!-- H1 Article -->
<a class="main-article-link" href="#">
<div class="main-article mb-5 pb-3">
<img src="{{ asset('build/images/meteor-shower.jpg') }}" alt="meteor shower">
... line 15
</div>
</a>
... lines 18 - 40
</div>
... lines 42 - 61
</div>
</div>
{% endblock %}

There are a few other images tags in this file. Search for <img. This is pointing to an uploaded file, not a static file - so, that's good. Ah, but this one needs to change: build/images/alien-profile.png:

... lines 1 - 2
{% block body %}
<div class="container">
<div class="row">
<!-- Article List -->
<div class="col-sm-12 col-md-8">
... lines 10 - 20
{% for article in articles %}
<div class="article-container my-1">
<a href="{{ path('article_show', {slug: article.slug}) }}">
... line 24
<div class="article-title d-inline-block pl-3 align-middle">
... lines 26 - 34
<span class="align-left article-details"><img class="article-author-img rounded-circle" src="{{ asset('build/images/alien-profile.png') }}"> {{ article.author }} </span>
... line 36
</div>
</a>
</div>
{% endfor %}
</div>
... lines 42 - 61
</div>
</div>
{% endblock %}

And one more, add build/ before space-ice.png:

... lines 1 - 2
{% block body %}
<div class="container">
<div class="row">
... lines 6 - 45
<div class="col-sm-12 col-md-4 text-center">
<div class="ad-space mx-auto mt-1 pb-2 pt-2">
<img class="advertisement-img" src="{{ asset('build/images/space-ice.png') }}">
... lines 49 - 50
</div>
... lines 52 - 60
</div>
</div>
</div>
{% endblock %}

Let's try it! Move over, refresh and... we got it! Inspect element: it's the final, versioned filename. Let's update the last img tags - they're in show.html.twig. Search for img tags again, then... build/, build/ and build/:

... lines 1 - 4
{% block content_body %}
<div class="row">
<div class="col-sm-12">
... line 8
<div class="show-article-title-container d-inline-block pl-3 align-middle">
... lines 10 - 11
<span class="align-left article-details"><img class="article-author-img rounded-circle" src="{{ asset('build/images/alien-profile.png') }}"> {{ article.author }} </span>
... lines 13 - 24
</div>
</div>
</div>
... lines 28 - 39
<div class="row">
<div class="col-sm-12">
... lines 42 - 44
<div class="row mb-5">
<div class="col-sm-12">
<img class="comment-img rounded-circle" src="{{ asset('build/images/astronaut-profile.png') }}">
... lines 48 - 54
</div>
</div>
{% for comment in article.nonDeletedComments %}
<div class="row">
<div class="col-sm-12">
<img class="comment-img rounded-circle" src="{{ asset('build/images/alien-profile.png') }}">
... lines 62 - 71
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
... lines 80 - 86

Click to go view one of the articles. These comment avatars are now using the system.

copyFiles() is nice because it lets you keep all your frontend files in the same directory... even if some need to be copied to the build directory. But to sweeten the deal, you're rewarded with free asset versioning.

By the way, this function was added by @Lyrkan, one of the core devs for Encore and... even though it's pretty simple, it's an absolutely brilliant implementation that I haven't seen used anywhere else. So, if you like it, give him a thanks on Symfony Slack or Twitter.

Next, let's create multiple entry points to support page-specific CSS and JavaScript.

Leave a comment!

  • 2020-04-28 Diego Aguiar

    Hey virgile sahaguian

    The whole point of using a hash as part of the file name is just for caching purposes. If you didn't change your image, then its name will be the same but whenever you change it, it will get a new name as soon as you compile your assets, so then, a browser will think it's a new image and will download it (and actually it is a new image)

    Cheers!

  • 2020-04-28 virgile sahaguian

    Hello SF! Fantastic tutorial
    I just didnt get the point of getting hash on my picture's names :(
    Could you briefly explain it ?

  • 2020-03-17 Anton Bagdatyev

    Cool! Thank you!

  • 2020-03-17 Vladimir Sadicov

    Hey Anton Bagdatyev

    Great question! Of course we can, and you will learn it at the end of this course! So keep learning!

    Cheers!

  • 2020-03-16 Anton Bagdatyev

    Cool! Can we do the same (add hash to the final name of the file) with CSS and JS files?

  • 2020-03-02 Diego Aguiar

    Ah ok, let's try something. In your CSS class, point directly to the "from" path. e.g.


    .item--fluid.bg{
    background-image: url(/assets/admin/media/bg-default.jpg)
    }


    I think, if you do that, Webpack will take care of the rest. Oh, but I think you have to be using SASS instead of CSS files

  • 2020-02-28 Francisco Cerezo Leal

    Hey Diego Aguiar

    It doesnt work.

    My from path is already set to from: './assets/admin/media/bg' pero the CSS file points to bg-default.jpg
    Inside the "to" folder 'build/admin/media/bg/' the file is bg-default.XXXXXXXX.jpg

    Any ideas?

  • 2020-02-28 Diego Aguiar

    Hey Francisco Cerezo Leal

    I think you just have to point to the "from" path, e.g. ./assets/admin/media/bg and Webpack should take care of the rest. Let me know if it worked :)

    Cheers!

  • 2020-02-28 Francisco Cerezo Leal

    Hi @all

    I have the next problem. A CSS file with:


    .item--fluid.bg{
    background-image: url(/admin/assets/custom/media/bg/bg-default.jpg)
    }

    When I use the copyFiles funcionality in the next way


    .copyFiles({
    from: './assets/admin/media/bg',
    to: 'admin/media/bg/[path][name].[ext]'
    })

    It works changing the CSS:


    .item--fluid.bg{
    background-image: url(/build/admin/media/bg/bg-default.jpg)
    }

    I want to use versioning for that:


    .copyFiles({
    from: './assets/admin/media/bg',
    to: 'admin/media/bg/[path][name].[hash:8].[ext]'
    })

    But then from CSS I don't know where the asset version file was created


    .item--fluid.bg{
    background-image: url(/build/admin/media/bg/bg-default.XXXXXXXX.jpg)
    }

    How can I fix it?

    Thanks

  • 2019-11-23 Victor Bocharsky

    Hey Kensley,

    Yes, actually you can point any image at any directory in your css or scss files. You can use whether relative or absolute path - the only requirement is that the path should be valid. Then Encore will notice it and copy to your build directory, and also will *rewrite* the paths in your css/scss files for you. So, make sure you're using correct paths to images, and it just should work :)

    Cheers!

  • 2019-11-21 kensley lewis

    Nice lesson. In regards to setting paths to images out of the build directory, is there anything similar we can do when linking images from style-sheets? Many thanks!

  • 2019-08-28 Dan Meigs

    Ryan,

    That was the missing link! I had no idea there was an asset() function that I could use outside of Twig. It works like a charm now.

    Thanks!

  • 2019-08-27 weaverryan

    Hey Dan Meigs!

    Ah... ok! In that case, the trick to getting this right will all be in the controller for that get_image AJAX call: it needs to return the *full*, final URL to the image so that your JavaScript can "dumbly" just print it. It will probably be something like this:


    use Symfony\Component\Asset\Packages;

    public function getImage(Packages $asset)
    {
    $imageUrl = $asset->getIUrl('static/image1.png');

    return $this->json([
    'image' => $imageUrl
    ]);
    }

    There are two keys here:

    1) That Packages service is basically the way that you call the asset() function (the one you normally use in Twig) from inside a controller. That's important because, assuming your app is setup correctly, the asset() function is smart enough to look in the Encore manifest.json file to get the final path to the image (including a version hash if you enable versioning).

    2) Am I assuming correctly that these static files are copied via copyFiles()? The second key is what string to pass to the getUrl() function. The easiest way to see what path you should pass here is to open up public/build/manifest.json and find the "image1.png" item in there and use whatever its "key" is. You should find something that looks *something* like "static/image1.png": "/build/static/image1.png". Whatever the key on the left is, that's what you should pass to getUrl().

    Let me know how that goes!

    Cheers!

  • 2019-08-27 Victor Bocharsky

    Hey Dan,

    Thanks for your feedback! Glad it works for you now.

    Cheers!

  • 2019-08-27 Dan Meigs

    Hey Ryan,

    Thanks for that answer, but my situation is a little more complicated than that. Based on user input, the get_image endpoint returns the path to one of five "static" assets that are committed to my repository. Because the jquery app does not know at compile time which image path will be returned, I can't import and display the image as directly as you showed.

    So...I can't wait for the more complex answer!

    Cheers!

  • 2019-08-26 weaverryan

    Hey Dan Meigs!

    Cool question :). The answer... depends a bit about the nature of these images. This get_image endpoint... is it returning an image path to some dynamic (e.g. uploaded?) icon image? Or is it literally just returning the path to some "static" asset that's committed to your repository? I think it's the second (because you mentioned the path is /build/static/image1.png). If so, follow-up question: does this get_image endpoint always return the exact same icon path? Or is this... dynamic (?) based on the user login or something different?

    And, in case you have the *simplest* situation (where you just want to get the image path to a static, committed image in your project), i'll give you the answer :). Let's assume the *source*, committed image (before Encore copies it) is assets/images/image1.png and you're JavaScript file lives at assets/js/app.js. In that case, the solution is this:


    // yes, you can import images! Use the relative path between the source files
    // imageUrl will be the final, "built" path - e.g. /build/static/image1.png
    import imageUrl from '../images/image1.png';

    showIcon() {
    writePage(data) {
    const html = eval(template)(data);
    this.$wrapper.append($.parseHTML(html));
    }

    const template = (data) => `
    <img src="${imageUrl}"/>
    `;

    Let me know if this helps... or if you have a more complex situation :).

    Cheers!

  • 2019-08-23 Dan Meigs

    Hi again!

    So, now I have a different problem...In one part of my app, I'm creating a portion of a page using a php template (an idea I got from your "JavaScript for PHP Geeks" tutorial"), which includes image tags from my static image directory. Unfortunately, I can't get the images to render.

    The code looks something like this:


    showIcon() {
    $.ajax({
    url: Routing.generate('get_image),
    method: 'GET'
    }).then((data) => {
    this.writePage(data);
    });
    }

    writePage(data) {
    const html = eval(template)(data);
    this.$wrapper.append($.parseHTML(html));
    }

    const template = (data) => `
    <img src="${data.image}"/>
    `;


    Before adding the hash to my static images, data.image was "/build/static/image1.png". That doesn't work now, so I figured a relative path was needed. I tried paths relative to the php app and templates relative to the php function called by the Ajax call, but neither worked. I'm sure there is a way to do this, I just can't figure it out.

    Can you show me the way?

  • 2019-08-23 Dan Meigs

    Thanks for the explanation Victor!

    I see now that the issue was discussed two chapters back. I guess I missed it!

  • 2019-08-23 Victor Bocharsky

    Hey Dan,

    That sounds very cool! About your problem - the easy fix! You just need to specify a relative path to the image in your CSS file - Webpack will automatically rewrite the relative path to the proper path with hash from the build/ directory. So, for example if you have this structure:


    assets
    /
    - css/
    -- app.css
    - images/
    -- static/
    --- background.jpg

    Then, you just need to specify path like "../images/static/background.jpg", i.e.:


    #container {
    min-height:100vh;
    position:relative;
    background: black url('../images/static/background.jpg') center top no-repeat;
    }

    Cheers!

  • 2019-08-23 Dan Meigs

    The new Webpack Encore is AWESOME! Reducing my build time from 6 minutes to 10 seconds makes my work so much easier. Thanks!

    I have a slight problem with hashed static files. They work great with Twig's asset() function, but I have one file that I call as a background by css:


    #container {
    min-height:100vh;
    position:relative;
    background: black url('/build/static/background.jpg') center top no-repeat;
    }

    How can I reference a static file from css?

    Thanks!

  • 2019-05-20 Krzysztof Krakowiak

    Thanks Vladimir, I will try again to resolve it.

  • 2019-05-17 Victor Bocharsky

    Hey Scottie,

    Ah, sorry, now I see! Totally makes sense, thanks for clarification and shared solution ;)

    Cheers!

  • 2019-05-17 Vladimir Sadicov

    Difficult to say, it depends on how you are including you font-awesome version. Are you using compiled css or it's scss version? probably your fonts files are placed in wrong directory, or you misconfigured fonts directory var, Fonts should be copied automatically.

    Cheers.

  • 2019-05-17 Skylar Scotlynn Gutman

    The hash files in this case are in the images folder.

  • 2019-05-16 Victor Bocharsky

    Hey Scottie,

    Thanks for sharing this example, but it really looks complicated. I just donwloaded the course code of this tutorial, went to the finish/ directory, ran "yarn install" & "yarn watch" and when "ls -l public/build" - I didn't see any hash in files, here's my output:

    -rw-r--r--  1 victor  staff    1952 May 16 13:39 0.css
    -rw-r--r-- 1 victor staff 5357 May 16 13:39 0.js
    -rw-r--r-- 1 victor staff 207206 May 16 13:39 1.js
    -rw-r--r-- 1 victor staff 5233 May 16 13:39 account.css
    -rw-r--r-- 1 victor staff 26630 May 16 13:39 admin_article_form.js
    -rw-r--r-- 1 victor staff 754963 May 16 13:39 app.css
    -rw-r--r-- 1 victor staff 7029 May 16 13:39 app.js
    -rw-r--r-- 1 victor staff 3226 May 16 13:39 article_show.css
    -rw-r--r-- 1 victor staff 4570 May 16 13:39 article_show.js
    -rw-r--r-- 1 victor staff 1167 May 16 13:39 entrypoints.json
    drwxr-xr-x 6 victor staff 192 May 16 13:39 fonts
    drwxr-xr-x 8 victor staff 256 May 16 13:39 images
    -rw-r--r-- 1 victor staff 2154 May 16 13:39 login.css
    -rw-r--r-- 1 victor staff 1740 May 16 13:39 manifest.json
    -rw-r--r-- 1 victor staff 26138 May 16 13:39 runtime.js
    -rw-r--r-- 1 victor staff 30873 May 16 13:39 vendors~admin_article_form.css
    -rw-r--r-- 1 victor staff 688827 May 16 13:39 vendors~admin_article_form.js
    -rw-r--r-- 1 victor staff 103969 May 16 13:39 vendors~admin_article_form~app.js
    -rw-r--r-- 1 victor staff 769144 May 16 13:39 vendors~admin_article_form~app~article_show.js
    -rw-r--r-- 1 victor staff 578820 May 16 13:39 vendors~app.js

    I only see hashes when build assets for production, i.e run "yarn build". So, probably some misconfiguration on your side.

    Cheers!

  • 2019-05-16 Victor Bocharsky

    Hey Scottie,

    Actually, you can enable versioning for production only and disable it for development, then you won't have this problem. Check the last chapter: https://symfonycasts.com/sc... - see ".enableVersioning(Encore.isProduction())" option. It should fix the problem you have :)

    Cheers!

  • 2019-05-15 Diego Aguiar

    Cool, thanks for sharing it!

  • 2019-05-15 Krzysztof Krakowiak

    Thanks Vladimir, I will check it. But I am really curious, why this works like that, I have checked npm folder for that package, but there wasn't anything special.

  • 2019-05-15 Vladimir Sadicov

    Hey Krzysztof Krakowiak

    Why you don't use Font awesome PRO from npm? In oficial fontawesome docs there are section how to instal PRO version with your personal token.

    Cheers!

  • 2019-05-15 Skylar Scotlynn Gutman

    Here is the kludge that I am using for the dev environment. I modified the webpack.config.js like this:


    const Encore = require('@symfony/webpack-encore');

    const assetDestinationProd = '[name].[hash:8].[ext]';
    const assetDestinationDev = '[name].[ext]';
    const destinationFilename = Encore.isProduction() ? assetDestinationProd : assetDestinationDev;

    Encore
    ...
    .copyFiles({
    from: './assets/images',
    to: 'images/[path]' + destinationFilename
    })
    .configureFilenames({
    images: destinationFilename,
    })
    ...

    I got this idea from https://github.com/Haehnche...

  • 2019-05-15 Victor Bocharsky

    Hey Scottie,

    Ah, now I see! It wasn't clear enough in your first comment :) Unfortunately, I don't know any plugin that would help with it. :/ Probably a good idea to suggest such improvement to Symfony Plugin.

    Cheers!

  • 2019-05-14 Krzysztof Krakowiak

    I have small issue with font awesome, I have pro version and I do not understand how it is, that when I use free version installed from npm it works (fonts are copied) and when I use my own then it doesn't work (fonts are not copied...). How does it work?

  • 2019-05-14 Skylar Scotlynn Gutman

    Thank you for the reply. But the problem is that I am using the image source to filename-with-hash conversion provided by the manifest.json. The link specified does not actually have a file. For example, using this tutorial, in the show.html.twig file, you will find {{ asset('build/images/alien-profile.png') }}. But the actual file is build/images/alien-profile.da9d186f.png. The manifest.json has the mapping for this conversion. And, because the file does not exist, phpstorm is "angry". I was hoping there might be a plugin to read the manifest.json to resolve this.

  • 2019-05-14 Victor Bocharsky

    Hey Scottie,

    Yes, there's a trick with it... Well, actually, not with asset() function in particular but with paths to files. First of all you need to install and *enable* Symfony Plugin. In its preferences, specify "public" (or the public directory for your Symfony project - it's web for old Symfony versions). And it should help IIRC. You can find how to do it in our free course about PhpStorm: https://symfonycasts.com/sc... .

    Another trick is right click on your public/ folder and in context menu choose "Mark directory as" -> "Resource route". After this PhpStorm will check all paths relative to the public folder and if it found a file - it won't highlight it.

    Cheers!

  • 2019-05-14 Skylar Scotlynn Gutman

    Hello guys,
    Is there a way to make phpstorm not be angry about the {{ asset('build/images/alien-profile.png') }}?

    Is there a webpack plugin or something to fix it?

  • 2019-05-13 Diego Aguiar

    Hey Marcel dos Santos

    It may cause an overhead but just at build time. Another thing to consider is that you will have duplicate images on your system, so if your production server is very low on disk space it might be a problem but I would not worry too much.

    Cheers!

  • 2019-05-13 Marcel dos Santos

    Hi, about this mapping between project filename's path and build filename's path can cause a overhead? I mean, it become slower? Or accessing manifest.json from file system are fast enough to use this approach?