Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CDN when combining assets with Symfony2 and Assetic

I would like to use CDN together with Assetic in my Symfony2 project. I am using the javascripts helper to combine several Javascript files:

{% javascripts
  '@MyBundle/Resources/public/js/file-1.js'
  '@MyBundle/Resources/public/js/file-2.js' %}
  <script src="{{ asset_url }}"></script>
{% endjavascripts %}

and in my config.yml file I have registered a CDN to be used in the assets:

framework:
    templating:
      assets_base_urls:
        http: [http://my.cdn.url]
        ssl: [https://my.cdn.url]

When dumping, I do get a combined file, but its url is a relative one, not one pointing to the CDN. For instance:

<script src="/js/c713f83.js"></script>

And the same happens when combining several CSS files. The only way I managed to get URLs using the CDN is through asset:

<img src="{{ asset('bundles/mybundle/images/logo.png') }} ">

Is there anything preventing Assetic from using the CDN hosts I have specified in my configuration?

like image 872
José M. Pérez Avatar asked May 07 '13 13:05

José M. Pérez


1 Answers

You have to pass the Assetic's generated asset_url to the asset() Twig's function :

{% javascripts
  '@MyBundle/Resources/public/js/file-1.js'
  '@MyBundle/Resources/public/js/file-2.js' %}
  <script src="{{ asset(asset_url) }}"></script>
{% endjavascripts %}

Be aware that in dev environment you will get URLs that look like http://my.cdn.url/app_dev.php/js/file-1.js. In order to prevent that you have to configure your dev environment so it doesn't use CDN :

# app/config/config_dev.yml
framework:
    templating:
        assets_base_urls:
            http: []
            ssl:  []

Remember dumping your assets with assetic:dump and, overall, remember that Assetic and the Symfony2 asset Twig function are two different things.

like image 100
iamdto Avatar answered Oct 17 '22 21:10

iamdto