prefixing asset path for files in Symfony2 and Twig

assets, php, symfony, twig

Solution

While you could easily introduce a new twig variable for that purpose (i.e. in your base template) ...

{% set asset_base = '//files/images' %}

... or create a static global twig variable ...

# app/config/config.yml
twig:
    globals:
        asset_base: //files/images

... and afterwards use it inside i.e. the `src` attribute of your `img` tag ...

<img src='{{ asset_base }}{{ asset(article.image) }}'/>

... symfony2 already provides this functionality in form of the `assets_base_urls` directive:

# app/config/config.yml
framework:
    templating:
        assets_base_urls:
            http:   [http://domain/files/images]
            ssl:    [https://domain/files/images]

You can aswell set the base urls both at once by providing a protocol-relative url:

framework:
    templating:
        assets_base_urls: //files/images

More information about the directive can be found in the documentation chapter FrameworkBundle Configuration#assets-base-urls.

Problem

I upoad my files to `web/files/images/` and i'm trying to link them using `asset` function: ``` <img src='{{ asset(article.image) }}'/> ``` but this produces URLs like `/img1.jpg` I need to prefix (setting a base folder) asset URLs to force it to make `/files/images/img1.jpg` How can I prefix `asset` urls?

Original source