This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Use Assetic for Asset Managment on Symfony 3.1 Applications

Updated on December 8, 2021

5 Min Read

In the previous installment, I added reCAPTCHA verification to Symfony 3.1 forms.

Assets are the files that give proper structure and layout to the websites and applications. They are usually composed of Javascript, CSS, and image files that are used for visual layout implementation of websites. Symfony offers an asset management Bundle called ASSETIC. Assetic is capable of loading assets from anywhere in the project, before serving them to the website using filters.

Assetic bundle Symfony 3.1

In addition, Assetic has methods to minify Javascript and CSS files and also be used to optimize images. The best thing is that Assetic can run from compilers like LESS and SASS.

To kick things off, I will show how to include Assetic in a Symfony Project.

The first step is to add Assetic bundle in the application. For this, sign into the Cloudways server. If you don’t have any account yet then signup and launch PHPStack server.

DO installation

open SSH Terminal using Master Credentials. Move to the application folder and run the following command.

$ composer require symfony/assetic-bundle

SSH terminal

Next, you need to enable it in AppKernel.php file. Open file and add the following line in the bundle array.

Assetic

To add Assetic bundle support, insert the following snippet in config.yml

assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        cssrewrite: ~

Assetic bundle is now added and properly available for use in the Symfony project.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Syntax : Adding Assets Using Assetic

Two main concepts in Assetic are Asset and Filters. I have already explained what assets are.  Filters are  usually used to provide separation between the asset files stored in the application and the files actually presented to the user. If Assetic is not in use, you can directly add Javascript  and CSS files to the code like this

<script src="{{ asset('js/script.js') }}"></script>

With Assetic, however, there is a different syntax to include the files you need to use. The URL is passed in twig tags ( {% %} ). In the HTML tag,  you only pass the URL keyword provided by Assetic bundle.

Loading Javascript Files Using Assetic

Javascript files can be added using javascript tags. For example:

{% javascripts '@AppBundle/Resources/public/js/*' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

As you can see, I passed the URL in javascript tag. In the HTML script tag, I only used the asset_url variable.

In the case of block tags as recommended by Symfony Standard Edition, the tags would look like:

{% block javascripts %}
    {% javascripts '@AppBundle/Resources/public/js/*' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

Note that I have written the URL with “*” . This means Assetic will load all the Javascript files present in the respective javascript folder. To load just one javascript file,  just pass the name of the file.

These assets are loaded from different locations because of Assetic Bundle. Since the actual URL is different, this might result in broken links.  

Loading Stylesheets Using Assetic

Using the same principles, stylesheets can be included. However,  this time I will use stylesheet tag. For the broken links, we could use a filter.  

{% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

cssrewrite filter provided by Assetic is an excellent way of fixing all broken links in the assets. For Symfony Standard Edition, the stylesheets in blocks look like:

{% block stylesheets %}
    {% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
        <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

Loading Images Using Assetic

To load images using Assetic,  image tags are used:

{% image '@AppBundle/Resources/public/images/example.jpg' %}
    <img src="{{ asset_url }}" alt="Example" />
{% endimage %}

Images could be optimized by using methods provided by Assetic Bundle. However, instead,  you may consider the LiipImagineBundle community bundle, which could optionally compress and manipulate images (rotate, resize, watermark, etc.) before serving them.

You might be interested in: How to Install Symfony 3 on Cloud Hosting

Loading Multiple Files Together

In addition to loading single files, Assetic also allows loading of multiple asset files in a single HTTP call. This decreases website loading time and the number of HTTP requests. The end result is a highly optimized application.

You can also load files from different bundles by combining them in one single Twig tag. See the example below:

{% javascripts
    '@AppBundle/Resources/public/js/*'
    '@AcmeBarBundle/Resources/public/js/form.js'
    '@AcmeBarBundle/Resources/public/js/calendar.js' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

Remember that in a development environment, all the files are served individually to debug errors and exceptions. However, in a production environment, all files are combined in a single script that is served to the browser. Third party assets in the application could be easily combined with other bundles.

Enabling Filters In Application

I have earlier shown what filters are and how to use them in code using the filter attribute. I will now show how they could be embedded in config.yml file.

Suppose, I want to use uglify filter for javascript. For this, add the following code in config.yml

assetic:
    filters:
        uglifyjs2:
            bin: /usr/local/bin/uglifyjs

How to Dump Asset Files

Assetic makes a URL for assets that are not even present locally or those that  don’t render anything in browser. The biggest advantage of these URL is that you can easily see the new state of assets. If there are changes in the state, Assetic provides methods to dump assets into physical  files in both development and production environments.

For Development Environment:

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

For Production Environment:

$ php bin/console assetic:dump

Note that if you make any changes to the asset files, you need to run dump commands again to apply the changes.

Final Words

In this article, I discussed the usage of Assetic bundle for asset management in Symfony. For in-depth information on how Assetic works, please visit the official Symfony blog. Assetic is a great bundle that is invaluable when managing and manipulating asset files including javascript ,CSS and images. Assetic dynamically generates URLs for the assets to quickly view new state. In the upcoming installment, I would discuss bundle management in Symfony 3.1. Here is a short introduction and list of major topics in this Symfony 3.1 series.

If you have a query or wish to contribute to the discussion, please leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now