Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Cookbook
  4. Assetic
  5. How to Use Assetic for Asset Management
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Assets
    • Including JavaScript Files
    • Including CSS Stylesheets
    • Including Images
    • Fixing CSS Paths with the cssrewrite Filter
    • Combining Assets
    • Using Named Assets
  • Filters
  • Controlling the URL Used
  • Dumping Asset Files
    • Dumping Asset Files in the prod Environment
    • Dumping Asset Files in the dev Environment

How to Use Assetic for Asset Management

Edit this page

Warning: You are browsing the documentation for Symfony 2.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Use Assetic for Asset Management

Assetic combines two major ideas: assets and filters. The assets are files such as CSS, JavaScript and image files. The filters are things that can be applied to these files before they are served to the browser. This allows a separation between the asset files stored in the application and the files actually presented to the user.

Without Assetic, you just serve the files that are stored in the application directly:

  • Twig
  • PHP
1
<script src="{{ asset('js/script.js') }}" type="text/javascript"></script>
1
<script src="<?php echo $view['assets']->getUrl('js/script.js') ?>" type="text/javascript"></script>

But with Assetic, you can manipulate these assets however you want (or load them from anywhere) before serving them. This means you can:

  • Minify and combine all of your CSS and JS files
  • Run all (or just some) of your CSS or JS files through some sort of compiler, such as LESS, SASS or CoffeeScript
  • Run image optimizations on your images

Assets

Using Assetic provides many advantages over directly serving the files. The files do not need to be stored where they are served from and can be drawn from various sources such as from within a bundle.

You can use Assetic to process CSS stylesheets, JavaScript files and images. The philosophy behind adding either is basically the same, but with a slightly different syntax.

Including JavaScript Files

To include JavaScript files, use the javascripts tag in any template:

  • Twig
  • PHP
1
2
3
{% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
<?php foreach ($view['assetic']->javascripts(
    array('@AcmeFooBundle/Resources/public/js/*')
) as $url): ?>
    <script type="text/javascript" src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

Note

If you're using the default block names from the Symfony Standard Edition, the javascripts tag will most commonly live in the javascripts block:

1
2
3
4
5
6
7
{# ... #}
{% block javascripts %}
    {% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
        <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}
{# ... #}

Tip

You can also include CSS Stylesheets: see How to Use Assetic for Asset Management.

In this example, all of the files in the Resources/public/js/ directory of the AcmeFooBundle will be loaded and served from a different location. The actual rendered tag might simply look like:

1
<script src="/app_dev.php/js/abcd123.js"></script>

This is a key point: once you let Assetic handle your assets, the files are served from a different location. This will cause problems with CSS files that reference images by their relative path. See How to Use Assetic for Asset Management.

Including CSS Stylesheets

To bring in CSS stylesheets, you can use the same methodologies seen above, except with the stylesheets tag:

  • Twig
  • PHP
1
2
3
{% stylesheets 'bundles/acme_foo/css/*' filter='cssrewrite' %}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
1
2
3
4
5
6
<?php foreach ($view['assetic']->stylesheets(
    array('bundles/acme_foo/css/*'),
    array('cssrewrite')
) as $url): ?>
    <link rel="stylesheet" href="<?php echo $view->escape($url) ?>" />
<?php endforeach; ?>

Note

If you're using the default block names from the Symfony Standard Edition, the stylesheets tag will most commonly live in the stylesheets block:

1
2
3
4
5
6
7
{# ... #}
{% block stylesheets %}
    {% stylesheets 'bundles/acme_foo/css/*' filter='cssrewrite' %}
        <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}
{# ... #}

But because Assetic changes the paths to your assets, this will break any background images (or other paths) that uses relative paths, unless you use the cssrewrite filter.

Note

Notice that in the original example that included JavaScript files, you referred to the files using a path like @AcmeFooBundle/Resources/public/file.js, but that in this example, you referred to the CSS files using their actual, publicly-accessible path: bundles/acme_foo/css. You can use either, except that there is a known issue that causes the cssrewrite filter to fail when using the @AcmeFooBundle syntax for CSS Stylesheets.

Including Images

To include an image you can use the image tag.

  • Twig
  • PHP
1
2
3
{% image '@AcmeFooBundle/Resources/public/images/example.jpg' %}
    <img src="{{ asset_url }}" alt="Example" />
{% endimage %}
1
2
3
4
5
<?php foreach ($view['assetic']->image(
    array('@AcmeFooBundle/Resources/public/images/example.jpg')
) as $url): ?>
    <img src="<?php echo $view->escape($url) ?>" alt="Example" />
<?php endforeach; ?>

You can also use Assetic for image optimization. More information in How to Use Assetic for Image Optimization with Twig Functions.

Fixing CSS Paths with the cssrewrite Filter

Since Assetic generates new URLs for your assets, any relative paths inside your CSS files will break. To fix this, make sure to use the cssrewrite filter with your stylesheets tag. This parses your CSS files and corrects the paths internally to reflect the new location.

You can see an example in the previous section.

Caution

When using the cssrewrite filter, don't refer to your CSS files using the @AcmeFooBundle syntax. See the note in the above section for details.

Combining Assets

One feature of Assetic is that it will combine many files into one. This helps to reduce the number of HTTP requests, which is great for front end performance. It also allows you to maintain the files more easily by splitting them into manageable parts. This can help with re-usability as you can easily split project-specific files from those which can be used in other applications, but still serve them as a single file:

  • Twig
  • PHP
1
2
3
4
5
6
{% javascripts
    '@AcmeFooBundle/Resources/public/js/*'
    '@AcmeBarBundle/Resources/public/js/form.js'
    '@AcmeBarBundle/Resources/public/js/calendar.js' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
8
9
<?php foreach ($view['assetic']->javascripts(
    array(
        '@AcmeFooBundle/Resources/public/js/*',
        '@AcmeBarBundle/Resources/public/js/form.js',
        '@AcmeBarBundle/Resources/public/js/calendar.js',
    )
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

In the dev environment, each file is still served individually, so that you can debug problems more easily. However, in the prod environment (or more specifically, when the debug flag is false), this will be rendered as a single script tag, which contains the contents of all of the JavaScript files.

Tip

If you're new to Assetic and try to use your application in the prod environment (by using the app.php controller), you'll likely see that all of your CSS and JS breaks. Don't worry! This is on purpose. For details on using Assetic in the prod environment, see How to Use Assetic for Asset Management.

And combining files doesn't only apply to your files. You can also use Assetic to combine third party assets, such as jQuery, with your own into a single file:

  • Twig
  • PHP
1
2
3
4
5
{% javascripts
    '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.js'
    '@AcmeFooBundle/Resources/public/js/*' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
8
<?php foreach ($view['assetic']->javascripts(
    array(
        '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.js',
        '@AcmeFooBundle/Resources/public/js/*',
    )
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

Using Named Assets

AsseticBundle configuration directives allow you to define named asset sets. You can do so by defining the input files, filters and output files in your configuration under the assetic section. Read more in the assetic config reference.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# app/config/config.yml
assetic:
    assets:
        jquery_and_ui:
            inputs:
                - '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.js'
                - '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.ui.js'
1
2
3
4
5
6
7
8
9
10
11
12
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:assetic="http://symfony.com/schema/dic/assetic">

    <assetic:config>
        <assetic:asset name="jquery_and_ui">
            <assetic:input>@AcmeFooBundle/Resources/public/js/thirdparty/jquery.js</assetic:input>
            <assetic:input>@AcmeFooBundle/Resources/public/js/thirdparty/jquery.ui.js</assetic:input>
        </assetic:asset>
    </assetic:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
// app/config/config.php
$container->loadFromExtension('assetic', array(
    'assets' => array(
        'jquery_and_ui' => array(
            'inputs' => array(
                '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.js',
                '@AcmeFooBundle/Resources/public/js/thirdparty/jquery.ui.js',
            ),
        ),
    ),
);

After you have defined the named assets, you can reference them in your templates with the @named_asset notation:

  • Twig
  • PHP
1
2
3
4
5
{% javascripts
    '@jquery_and_ui'
    '@AcmeFooBundle/Resources/public/js/*' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
8
<?php foreach ($view['assetic']->javascripts(
    array(
        '@jquery_and_ui',
        '@AcmeFooBundle/Resources/public/js/*',
    )
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

Filters

Once they're managed by Assetic, you can apply filters to your assets before they are served. This includes filters that compress the output of your assets for smaller file sizes (and better front-end optimization). Other filters can compile JavaScript file from CoffeeScript files and process SASS into CSS. In fact, Assetic has a long list of available filters.

Many of the filters do not do the work directly, but use existing third-party libraries to do the heavy-lifting. This means that you'll often need to install a third-party library to use a filter. The great advantage of using Assetic to invoke these libraries (as opposed to using them directly) is that instead of having to run them manually after you work on the files, Assetic will take care of this for you and remove this step altogether from your development and deployment processes.

To use a filter, you first need to specify it in the Assetic configuration. Adding a filter here doesn't mean it's being used - it just means that it's available to use (you'll use the filter below).

For example to use the UglifyJS JavaScript minifier the following config should be added:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# app/config/config.yml
assetic:
    filters:
        uglifyjs2:
            bin: /usr/local/bin/uglifyjs
1
2
3
4
5
6
<!-- app/config/config.xml -->
<assetic:config>
    <assetic:filter
        name="uglifyjs2"
        bin="/usr/local/bin/uglifyjs" />
</assetic:config>
1
2
3
4
5
6
7
8
// app/config/config.php
$container->loadFromExtension('assetic', array(
    'filters' => array(
        'uglifyjs2' => array(
            'bin' => '/usr/local/bin/uglifyjs',
        ),
    ),
));

Now, to actually use the filter on a group of JavaScript files, add it into your template:

  • Twig
  • PHP
1
2
3
{% javascripts '@AcmeFooBundle/Resources/public/js/*' filter='uglifyjs2' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
<?php foreach ($view['assetic']->javascripts(
    array('@AcmeFooBundle/Resources/public/js/*'),
    array('uglifyjs2')
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

A more detailed guide about configuring and using Assetic filters as well as details of Assetic's debug mode can be found in How to Minify CSS/JS Files (Using UglifyJS and UglifyCSS).

Controlling the URL Used

If you wish to, you can control the URLs that Assetic produces. This is done from the template and is relative to the public document root:

  • Twig
  • PHP
1
2
3
{% javascripts '@AcmeFooBundle/Resources/public/js/*' output='js/compiled/main.js' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
<?php foreach ($view['assetic']->javascripts(
    array('@AcmeFooBundle/Resources/public/js/*'),
    array(),
    array('output' => 'js/compiled/main.js')
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>

Note

Symfony also contains a method for cache busting, where the final URL generated by Assetic contains a query parameter that can be incremented via configuration on each deployment. For more information, see the FrameworkBundle Configuration ("framework") configuration option.

Dumping Asset Files

In the dev environment, Assetic generates paths to CSS and JavaScript files that don't physically exist on your computer. But they render nonetheless because an internal Symfony controller opens the files and serves back the content (after running any filters).

This kind of dynamic serving of processed assets is great because it means that you can immediately see the new state of any asset files you change. It's also bad, because it can be quite slow. If you're using a lot of filters, it might be downright frustrating.

Fortunately, Assetic provides a way to dump your assets to real files, instead of being generated dynamically.

Dumping Asset Files in the prod Environment

In the prod environment, your JS and CSS files are represented by a single tag each. In other words, instead of seeing each JavaScript file you're including in your source, you'll likely just see something like this:

1
<script src="/js/abcd123.js"></script>

Moreover, that file does not actually exist, nor is it dynamically rendered by Symfony (as the asset files are in the dev environment). This is on purpose - letting Symfony generate these files dynamically in a production environment is just too slow.

Instead, each time you use your app in the prod environment (and therefore, each time you deploy), you should run the following task:

1
$ php app/console assetic:dump --env=prod --no-debug

This will physically generate and write each file that you need (e.g. /js/abcd123.js). If you update any of your assets, you'll need to run this again to regenerate the file.

Dumping Asset Files in the dev Environment

By default, each asset path generated in the dev environment is handled dynamically by Symfony. This has no disadvantage (you can see your changes immediately), except that assets can load noticeably slow. If you feel like your assets are loading too slowly, follow this guide.

First, tell Symfony to stop trying to process these files dynamically. Make the following change in your config_dev.yml file:

  • YAML
  • XML
  • PHP
1
2
3
# app/config/config_dev.yml
assetic:
    use_controller: false
1
2
<!-- app/config/config_dev.xml -->
<assetic:config use-controller="false" />
1
2
3
4
// app/config/config_dev.php
$container->loadFromExtension('assetic', array(
    'use_controller' => false,
));

Next, since Symfony is no longer generating these assets for you, you'll need to dump them manually. To do so, run the following:

1
$ php app/console assetic:dump

This physically writes all of the asset files you need for your dev environment. The big disadvantage is that you need to run this each time you update an asset. Fortunately, by passing the --watch option, the command will automatically regenerate assets as they change:

1
$ php app/console assetic:dump --watch

Since running this command in the dev environment may generate a bunch of files, it's usually a good idea to point your generated assets files to some isolated directory (e.g. /js/compiled), to keep things organized:

  • Twig
  • PHP
1
2
3
{% javascripts '@AcmeFooBundle/Resources/public/js/*' output='js/compiled/main.js' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
<?php foreach ($view['assetic']->javascripts(
    array('@AcmeFooBundle/Resources/public/js/*'),
    array(),
    array('output' => 'js/compiled/main.js')
) as $url): ?>
    <script src="<?php echo $view->escape($url) ?>"></script>
<?php endforeach; ?>
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Code consumes server resources. Blackfire tells you how

    Code consumes server resources. Blackfire tells you how

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Shane Preece, a Symfony contributor

    Thanks Shane Preece (@shane) for being a Symfony contributor

    1 commit • 16 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia