Loading assets from a different server

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:

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

{% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
{% endjavascripts %}

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

    engines: ['twig']
    assets_base_urls: http://assets.yourdomain.com
    assets_base_urls: ~ # Files are loaded with relative path

Decorating Blocks in Twig

This is a simple trick how you can dynamically decorate a block in Twig.

Let’s say your design has a fanzy sidebar but you only want to display it when it has some content. In Twig you would usually solve this creating two seperate base templates. One, which includes a block named “sidebar”, and another one without it. This is quite easy, but then you’ll have to make sure you’re using the right base template. In addition you’ll have to maintain two base templates, even if they’re identical except for the sidebar.

So is there something else we could do, to make life more easy? Sure, we could put some more logic into to base template: Let’s check if the sidebar block has content! In that case we will display the content of the block embedded in some extra HTML.

This is how a base.html.twig might look like:

{% set sidebarContent = block("sidebar") %}
{% if sidebarContent %}
{% endif %}

First we’re fetching the content of the block into a variable with Twig’s block function.¬† Now we can check if there’s some content in it, so we can display the HTML container and the sidebar content on demand. Note that you have to use the raw filter on the block content since it is already sanitized HTML.