简体   繁体   中英

prefixing asset path for files in Symfony2 and Twig

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?

While you could easily introduce a new twig variable for that purpose (ie 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 ie 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 .

Note that since symfony 2.7 the assets_base_urls solution from @nifr will only work with valid urls, not with relative pathes.

See here https://github.com/symfony/symfony/issues/14332

The solution for > 2.7 is to use the new assets component for relative base path as prefix.

framework:
    assets:
        base_path: 'assets'

If you don't want to prefix all assets, the asset helper provides another really nice way to do this using packages.

Packages have a name and can have other settings, such as the version and the base path. You configure packages in the configuration and you can set the name of the package to use in the second argument of the asset function.

In your case:

framework:
    templating:
        packages:
            images:
                base_url: /web/files/images # can also be scheme specific

And then in you template:

<img src="{{ asset('...', 'images'). }}">

More information: http://symfony.com/doc/current/components/templating/helpers/assetshelper.html#multiple-packages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM