The Blog

Loading assets from a different server Posted on

In a production environment you’ll eventually want to load assets (images, CSS and JS) from a different server. Perhaps you’re running your own asset server or you’re even using a CDN. This will require the files to be linked with an absolute URL. But in your development environment you don’t want this – you want assets to be loaded directly from the same server.

So this is what you do. Use Symfony’s asset() function for every asset you want to load from the asset server:

<link rel="stylesheet" href="{{ asset('css/style.css') }}" type="text/css" media="all" />
<script type="text/javascript" src="{{ asset('js/scrips.js') }}"></script>
<img src="{{ asset('images/teaser.png') }}" />

If you’re using Assetic you’ll have to add the asset() function to asset_url:

{% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset(asset_url) }}"></script>
{% endjavascripts %}

Now you can have different configuration for your production and development environment:

framework:
  templating:
    engines: ['twig']
    assets_base_urls: http://assets.yourdomain.com
framework:
  templating:
    assets_base_urls: ~ # Files are loaded with relative path
This entry was posted in Symfony2. Bookmark the permalink.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *



CAPTCHA
Change the CAPTCHA codeSpeak the CAPTCHA code